Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

OOPS in Java

Java OOPs Concepts

Simula is considered as the first object-oriented programming language. The programming paradigm where everything is represented as an object, is known as truly object-oriented programming language.

Smalltalk is considered as the first truly object-oriented programming language.

OOPs (Object Oriented Programming System)

java oops concepts

Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:

  • Object

  • Class

  • Inheritance

  • Polymorphism

  • Abstraction

  • Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

polymorphism in java oops concepts

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.

In java, we use abstract class and interface to achieve abstraction.

encapsulation in java oops concepts

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.


Advantage of OOPs over Procedure-oriented programming language

1)OOPs makes development and maintenance easier where as in Procedure-oriented programming language it is not easy to manage if code grows as project size grows.

2)OOPs provides data hiding whereas in Procedure-oriented programming language a global data can be accessed from anywhere.

3)OOPs provides ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language.


Global Data

Object Data

What is difference between object-oriented programming language and object-based programming language?

Object based programming language follows all the features of OOPs except Inheritance. JavaScript and VBScript are examples of object based programming languages.

Java Naming conventions

Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method etc.

But, it is not forced to follow. So, it is known as convention not rule.

All the classes, interfaces, packages, methods and fields of java programming language are given according to java naming convention.

 

 

Advantage of naming conventions in java

By using standard Java naming conventions, you make your code easier to read for yourself and for other programmers. Readability of Java program is very important. It indicates that less time is spent to figure out what the code does.

Name

Convention

class name

should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc.

interface name

should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc.

method name

should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc.

variable name

should start with lowercase letter e.g. firstName, orderNumber etc.

package name

should be in lowercase letter e.g. java, lang, sql, util etc.

constants name

should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.

CamelCase in java naming conventions

Java follows camelcase syntax for naming the class, interface, method and variable.

If name is combined with two words, second word will start with uppercase letter always e.g. actionPerformed(), firstName, ActionEvent, ActionListener etc.

Object and Class in Java

Object is the physical as well as logical entity whereas class is the logical entity only.

Object in Java

object in java

An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be physical or logical (tangible and intangible). The example of intangible object is banking system.

An object has three characteristics:

  • state: represents data (value) of an object.

  • behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.

  • identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance(result) of a class.

Object Definitions:

  • Object is a real world entity.

  • Object is a run time entity.

  • Object is an entity which has state and behavior.

  • Object is an instance of a class.

Class in Java

A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

  • fields

  • methods

  • constructors

  • blocks

  • nested class and interface

Syntax to declare a class:

  1. class classname{  

  2.     field;  

  3.     method;  }  

Instance variable in Java

A variable which is created inside the class but outside the method, is known as instance variable. Instance variable doesn't get memory at compile time. It gets memory at run time when object(instance) is created. That is why, it is known as instance variable.


Method in Java

In java, a method is like function i.e. used to expose behavior of an object.

Advantage of Method

  • Code Reusability

  • Code Optimization


new keyword in Java

The new keyword is used to allocate memory at run time. All objects get memory in Heap memory area.

Object and Class Example: main within class

In this example, we have created a Student class that have two data members id and name. We are creating the object of the Student class by new keyword and printing the objects value.

Here, we are creating main() method inside the class.

File: Student.java

  1. class Student{  

  2.  int id;//field or data member or instance variable  

  3.  String name;  

  4.   

  5.  public static void main(String args[]){  

  6.   Student s1=new Student();//creating an object of Student  

  7.   System.out.println(s1.id);//accessing member through reference variable  

  8.   System.out.println(s1.name);  

  9.  }  

  10. }  


Output:

null

 

Object and Class Example: main outside class

In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class.

We can have multiple classes in different java files or single java file. If you define multiple classes in a single java source file, it is a good idea to save the file name with the class name which has main() method.

File: TestStudent1.java

  1. class Student{  

  2.  int id;  

  3.  String name;  

  4. }  

  5. class TestStudent1{  

  6.  public static void main(String args[]){  

  7.   Student s1=new Student();  

  8.   System.out.println(s1.id);  

  9.   System.out.println(s1.name);  

  10.  }  

  11. }  

Output:

null

3 Ways to initialize object

There are 3 ways to initialize object in java.

  1. By reference variable

  2. By method

  3. By constructor

1) Object and Class Example: Initialization through reference

Initializing object simply means storing data into object. Let's see a simple example where we are going to initialize object through reference variable.

File: TestStudent2.java

  1. class Student{  

  2.  int id;  

  3.  String name;  

  4. }  

  5. class TestStudent2{  

  6.  public static void main(String args[]){  

  7.   Student s1=new Student();  

  8.   s1.id=101;  

  9.   s1.name="Sonoo";  

  10.   System.out.println(s1.id+" "+s1.name);//printing members with a white space  

  11.  }  

  12. }  

Output:

101 Sonoo

We can also create multiple objects and store information in it through reference variable.

File: TestStudent3.java

  1. class Student{  

  2.  int id;  

  3.  String name;  

  4. }  

  5. class TestStudent3{  

  6.  public static void main(String args[]){  

  7.   //Creating objects  

  8.   Student s1=new Student();  

  9.   Student s2=new Student();  

  10.   //Initializing objects  

  11.   s1.id=101;  

  12.   s1.name="Sonoo";  

  13.   s2.id=102;  

  14.   s2.name="Amit";  

  15.   //Printing data  

  16.   System.out.println(s1.id+" "+s1.name);  

  17.   System.out.println(s2.id+" "+s2.name);  

  18.  }  

  19. }  

Output:

101 Sonoo

102 Amit

2) Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.

File: TestStudent4.java

  1. class Student{  

  2.  int rollno;  

  3.  String name;  

  4.  void insertRecord(int r, String n){  

  5.   rollno=r;  

  6.   name=n;  

  7.  }  

  8.  void displayInformation(){System.out.println(rollno+" "+name);}  

  9. }  

  10. class TestStudent4{  

  11.  public static void main(String args[]){  

  12.   Student s1=new Student();  

  13.   Student s2=new Student();  

  14.   s1.insertRecord(111,"Karan");  

  15.   s2.insertRecord(222,"Aryan");  

  16.   s1.displayInformation();  

  17.   s2.displayInformation();  

  18.  }  

  19. }  

Output:

111 Karan

222 Aryan

Object in java with values

As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.

3) Object and Class Example: Initialization through constructor

 

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

  1. class Employee{  

  2.     int id;  

  3.     String name;  

  4.     float salary;  

  5.     void insert(int i, String n, float s) {  

  6.         id=i;  

  7.         name=n;  

  8.         salary=s;  

  9.     }  

  10.     void display(){System.out.println(id+" "+name+" "+salary);}  

  11. }  

  12. public class TestEmployee {  

  13. public static void main(String[] args) {  

  14.     Employee e1=new Employee();  

  15.     Employee e2=new Employee();  

  16.     Employee e3=new Employee();  

  17.     e1.insert(101,"ajeet",45000);  

  18.     e2.insert(102,"irfan",25000);  

  19.     e3.insert(103,"nakul",55000);  

  20.     e1.display();  

  21.     e2.display();  

  22.     e3.display();  

  23. }  

  24. }  

Output:

101 ajeet 45000.0

102 irfan 25000.0

103 nakul 55000.0

 

Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.

File: TestRectangle1.java

  1. class Rectangle{  

  2.  int length;  

  3.  int width;  

  4.  void insert(int l, int w){  

  5.   length=l;  

  6.   width=w;  

  7.  }  

  8.  void calculateArea(){System.out.println(length*width);}  

  9. }  

  10. class TestRectangle1{  

  11.  public static void main(String args[]){  

  12.   Rectangle r1=new Rectangle();  

  13.   Rectangle r2=new Rectangle();  

  14.   r1.insert(11,5);  

  15.   r2.insert(3,15);  

  16.   r1.calculateArea();  

  17.   r2.calculateArea();  

  18. }  

  19. }  

Output:

55 

45     

Anonymous object

Anonymous simply means nameless. An object which has no reference is known as anonymous object. It can be used at the time of object creation only.

If you have to use an object only once, anonymous object is a good approach. For example:

  1. new Calculation();//anonymous object  

Calling method through reference:

  1. Calculation c=new Calculation();  

  2. c.fact(5);  

Calling method through anonymous object

  1. new Calculation().fact(5);  

Let's see the full example of anonymous object in java.

  1. class Calculation{  

  2.  void fact(int  n){  

  3.   int fact=1;  

  4.   for(int i=1;i<=n;i++){  

  5.    fact=fact*i;  

  6.   }  

  7.  System.out.println("factorial is "+fact);  

  8. }  

  9. public static void main(String args[]){  

  10.  new Calculation().fact(5);//calling method with anonymous object  

  11. }}  

Output:

Factorial is 120

Creating multiple objects by one type only

We can create multiple objects by one type only as we do in case of primitives.

Initialization of primitive variables:

  1. int a=10, b=20;  

Initialization of refernce variables:

  1. Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects  

Let's see the example:

  1. class Rectangle{  

  2.  int length;  

  3.  int width;  

  4.  void insert(int l,int w){  

  5.   length=l;  

  6.   width=w;  

  7.  }  

  8.  void calculateArea(){System.out.println(length*width);}  

  9. }  

  10. class TestRectangle2{  

  11.  public static void main(String args[]){  

  12.   Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects  

  13.   r1.insert(11,5);  

  14.   r2.insert(3,15);  

  15.   r1.calculateArea();  

  16.   r2.calculateArea();  

  17. }  

  18. }  

Output:

55 

45     

 

 

Real World Example: Account

File: TestAccount.java

  1. class Account{  

  2. int acc_no;  

  3. String name;  

  4. float amount;  

  5. void insert(int a,String n,float amt){  

  6. acc_no=a;  

  7. name=n;  

  8. amount=amt;  

  9. }  

  10. void deposit(float amt){  

  11. amount=amount+amt;  

  12. System.out.println(amt+" deposited");  

  13. }  

  14. void withdraw(float amt){  

  15. if(amount<amt){  

  16. System.out.println("Insufficient Balance");  

  17. }else{  

  18. amount=amount-amt;  

  19. System.out.println(amt+" withdrawn");  

  20. }  

  21. }  

  22. void checkBalance(){System.out.println("Balance is: "+amount);}  

  23. void display(){System.out.println(acc_no+" "+name+" "+amount);}  

  24. }  

  25.   

  26. class TestAccount{  

  27. public static void main(String[] args){  

  28. Account a1=new Account();  

  29. a1.insert(832345,"Ankit",1000);  

  30. a1.display();  

  31. a1.checkBalance();  

  32. a1.deposit(40000);  

  33. a1.checkBalance();  

  34. a1.withdraw(15000);  

  35. a1.checkBalance();  

  36. }}   

Output:

832345 Ankit 1000.0

Balance is: 1000.0

40000.0 deposited

Balance is: 41000.0

15000.0 withdrawn

Balance is: 26000.0


Constructor in Java

Constructor in java is a special type of method that is used to initialize the object.

Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

  1. Constructor name must be same as its class name

  2. Constructor must have no explicit return type

Types of java constructors

There are two types of constructors:

  1. Default constructor (no-arg constructor)

  2. Parameterized constructor

Java Default Constructor

A constructor that have no parameter is known as default constructor.

1. Syntax of default constructor:

2. <class_name>(){}  

3. Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.

  1. Bike1(){System.out.println("Bike is created");}  

  2. public static void main(String args[]){  

  3. Bike1 b=new Bike1();  

  4. }  

  5. }  

Output:

Bike is created

Rule: If there is no constructor in a class

default constructor

Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on the type.

Example of default constructor that displays the default values

  1. class Student3{  

  2. int id;  

  3. String name;  

  4.   

  5. void display(){System.out.println(id+" "+name);}  

  6.   

  7. public static void main(String args[]){  

  8. Student3 s1=new Student3();  

  9. Student3 s2=new Student3();  

  10. s1.display();  

  11. s2.display();  

  12. }  

  13. }  

Output:

0 null

0 null

Explanation:In the above class,you are not creating any constructor so compiler provides you a default 

constructor.Here 0 and null values are provided by default constructor.

 Java parameterized constructor

A constructor that have parameters is known as parameterized constructor.  

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.  

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. 

We can have any number of parameters in the constructor.

  1. class Student4{  

  2.     int id;  

  3.     String name;  

  4.       

  5.     Student4(int i,String n){  

  6.     id = i;  

  7.     name = n;  

  8.     }  

  9.     void display(){System.out.println(id+" "+name);}  

  10.    

  11.     public static void main(String args[]){  

  12.     Student4 s1 = new Student4(111,"Karan");  

  13.     Student4 s2 = new Student4(222,"Aryan");  

  14.     s1.display();  

  15.     s2.display();  

  16.    }  

  17. }  

Output:

111 Karan

222 Aryan

 

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

 

 Example of Constructor Overloading

  1. class Student5{  

  2.     int id;  

  3.     String name;  

  4.     int age;  

  5.     Student5(int i,String n){  

  6.     id = i;  

  7.     name = n;  

  8.     }  

  9.     Student5(int i,String n,int a){  

  10.     id = i;  

  11.     name = n;  

  12.     age=a;  

  13.     }  

  14.     void display(){System.out.println(id+" "+name+" "+age);}  

  15.    

  16.     public static void main(String args[]){  

  17.     Student5 s1 = new Student5(111,"Karan");  

  18.     Student5 s2 = new Student5(222,"Aryan",25);  

  19.     s1.display();  

  20.     s2.display();  

  21.    }  }  

Output:

111 Karan 0

222 Aryan 25

 

Difference between constructor and method in java


Java Constructor

Java Method

Constructor is used to initialize the state of an object.

Method is used to expose behaviour of an object.

Constructor must not have return type.

Method must have return type.

Constructor is invoked implicitly.

Method is invoked explicitly.

The java compiler provides a default constructor if you don't have any constructor.

Method is not provided by compiler in any case.

Constructor name must be same as the class name.

Method name may or may not be same as class name.

Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

  • By constructor

  • By assigning the values of one object into another

  • By clone() method of Object class

In this example, we are going to copy the values

  1.    class Student6{  

  2.  int id;  

  3.     String name;  

  4.     Student6(int i,String n){  

  5.     id = i;  

  6.     name = n;  

  7.     }  

  8.       

  9.     Student6(Student6 s){  

  10.     id = s.id;  

  11.     name =s.name;  

  12.     }  

  13.     void display(){System.out.println(id+" "+name);}  

  14.    

  15.     public static void main(String args[]){  

  16.     Student6 s1 = new Student6(111,"Karan");  

  17.     Student6 s2 = new Student6(s1);  

  18.     s1.display();  

  19.     s2.display();  

  20.    }  

  21. }  

Output:

111 Karan

111 Karan


Copying values without constructor

We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.

  1. class Student7{  

  2.     int id;  

  3.     String name;  

  4.     Student7(int i,String n){  

  5.     id = i;  

  6.     name = n;  

  7.     }  

  8.     Student7(){}  

  9.     void display(){System.out.println(id+" "+name);}  

  10.    

  11.     public static void main(String args[]){  

  12.     Student7 s1 = new Student7(111,"Karan");  

  13.     Student7 s2 = new Student7();  

  14.     s2.id=s1.id;  

  15.     s2.name=s1.name;  

  16.     s1.display();  

  17.     s2.display();  

  18.    }  

  19. }  

Output:

111 Karan

111 Karan


Q) Does constructor return any value?

Ans:yes, that is current class instance (You cannot use return type yet it returns a value).


Can constructor perform other tasks instead of initialization?

Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the constructor as you perform in the method.

Java static keyword

The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.

The static can be:

  1. variable (also known as class variable)

  2. method (also known as class method)

  3. block

  4. nested class


1) Java static variable

If you declare any variable as static, it is known static variable.

  • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.

  • The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable

  1. class Student{  

  2.      int rollno;  

  3.      String name;  

  4.      String college="ITS";  

  5. }  

Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once.

Java static property is shared to all objects.

Example of static variable

  1. //Program of static variable  

  2.   

  3. class Student8{  

  4.    int rollno;  

  5.    String name;  

  6.    static String college ="ITS";  

  7.      

  8.    Student8(int r,String n){  

  9.    rollno = r;  

  10.    name = n;  

  11.    }  

  12.  void display (){System.out.println(rollno+" "+name+" "+college);}  

  13.   

  14.  public static void main(String args[]){  

  15.  Student8 s1 = new Student8(111,"Karan");  

  16.  Student8 s2 = new Student8(222,"Aryan");  

  17.    

  18.  s1.display();  

  19.  s2.display();  

  20.  }  

  21. }  

Output:111 Karan ITS

       222 Aryan ITS

Static Variable


Program of counter without static variable

In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.

  1. class Counter{  

  2. int count=0;//will get memory when instance is created  

  3.   

  4. Counter(){  

  5. count++;  

  6. System.out.println(count);  

  7. }  

  8.   

  9. public static void main(String args[]){  

  10.   

  11. Counter c1=new Counter();  

  12. Counter c2=new Counter();  

  13. Counter c3=new Counter();  

  14.   

  15.  }  

  16. }  


Output:1

       1

       1


Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.

  1. class Counter2{  

  2. static int count=0;//will get memory only once and retain its value  

  3.   

  4. Counter2(){  

  5. count++;  

  6. System.out.println(count);  

  7. }  

  8.   

  9. public static void main(String args[]){  

  10.   

  11. Counter2 c1=new Counter2();  

  12. Counter2 c2=new Counter2();  

  13. Counter2 c3=new Counter2();  

  14.   

  15.  }  

  16. }  


Output:1

       2

       3


2) Java static method

If you apply static keyword with any method, it is known as static method.

  • A static method belongs to the class rather than object of a class.

  • A static method can be invoked without the need for creating an instance of a class.

  • static method can access static data member and can change the value of it.

 

Example of static method

  1. //Program of changing the common property of all objects(static field).  

  2.   

  3. class Student9{  

  4.      int rollno;  

  5.      String name;  

  6.      static String college = "ITS";  

  7.        

  8.      static void change(){  

  9.      college = "BBDIT";  

  10.      }  

  11.   

  12.      Student9(int r, String n){  

  13.      rollno = r;  

  14.      name = n;  

  15.      }  

  16.   

  17.      void display (){System.out.println(rollno+" "+name+" "+college);}  

  18.   

  19.     public static void main(String args[]){  

  20.     Student9.change();  

  21.   

  22.     Student9 s1 = new Student9 (111,"Karan");  

  23.     Student9 s2 = new Student9 (222,"Aryan");  

  24.     Student9 s3 = new Student9 (333,"Sonoo");  

  25.   

  26.     s1.display();  

  27.     s2.display();  

  28.     s3.display();  

  29.     }  

  30. }  


Output:111 Karan BBDIT

       222 Aryan BBDIT

       333 Sonoo BBDIT


Another example of static method that performs normal calculation

  1. //Program to get cube of a given number by static method  

  2.   

  3. class Calculate{  

  4.   static int cube(int x){  

  5.   return x*x*x;  

  6.   }  

  7.   

  8.   public static void main(String args[]){  

  9.   int result=Calculate.cube(5);  

  10.   System.out.println(result);  

  11.   }  

  12. }  


Output:125

Restrictions for static method

There are two main restrictions for the static method. They are:


  1. The static method can not use non static data member or call non-static method directly.

  2. this and super cannot be used in static context.

  1. class A{  

  2.  int a=40;//non static  

  3.    

  4.  public static void main(String args[]){  

  5.   System.out.println(a);  

  6.  }  

  7. }        


Output:Compile Time Error


Q) why java main method is static?

Ans) because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.


3) Java static block

  • Is used to initialize the static data member.

  • It is executed before main method at the time of classloading.

Example of static block

  1. class A2{  

  2.   static{System.out.println("static block is invoked");}  

  3.   public static void main(String args[]){  

  4.    System.out.println("Hello main");  

  5.   }  

  6. }  

Test it Now

Output:static block is invoked

       Hello main


Q) Can we execute a program without main() method?

Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.

  1. class A3{  

  2.   static{  

  3.   System.out.println("static block is invoked");  

  4.   System.exit(0);  

  5.   }  

  6. }  


Output:static block is invoked (if not JDK7)

In JDK7 and above, output will be:

Output:Error: Main method not found in class A3, please define the main method as:

public static void main(String[] args)


this keyword in java

There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

  1. this can be used to refer current class instance variable.

  2. this can be used to invoke current class method (implicitly)

  3. this() can be used to invoke current class constructor.

  4. this can be passed as an argument in the method call.

  5. this can be passed as argument in the constructor call.

  6. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usage of this keyword.

java this keyword


1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.

Understanding the problem without this keyword

Let's understand the problem if we don't use this keyword by the example given below:

  1. class Student{  

  2. int rollno;  

  3. String name;  

  4. float fee;  

  5. Student(int rollno,String name,float fee){  

  6. rollno=rollno;  

  7. name=name;  

  8. fee=fee;  

  9. }  

  10. void display(){System.out.println(rollno+" "+name+" "+fee);}  

  11. }  

  12. class TestThis1{  

  13. public static void main(String args[]){  

  14. Student s1=new Student(111,"ankit",5000f);  

  15. Student s2=new Student(112,"sumit",6000f);  

  16. s1.display();  

  17. s2.display();  

  18. }}  

Output:

0 null 0.0

0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword

  1. class Student{  

  2. int rollno;  

  3. String name;  

  4. float fee;  

  5. Student(int rollno,String name,float fee){  

  6. this.rollno=rollno;  

  7. this.name=name;  

  8. this.fee=fee;  

  9. }  

  10. void display(){System.out.println(rollno+" "+name+" "+fee);}  

  11. }  

  12.   

  13. class TestThis2{  

  14. public static void main(String args[]){  

  15. Student s1=new Student(111,"ankit",5000f);  

  16. Student s2=new Student(112,"sumit",6000f);  

  17. s1.display();  

  18. s2.display();  

  19. }}  

Output:

111 ankit 5000

112 sumit 6000

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:

Program where this keyword is not required

  1. class Student{  

  2. int rollno;  

  3. String name;  

  4. float fee;  

  5. Student(int r,String n,float f){  

  6. rollno=r;  

  7. name=n;  

  8. fee=f;  

  9. }  

  10. void display(){System.out.println(rollno+" "+name+" "+fee);}  

  11. }  

  12.   

  13. class TestThis3{  

  14. public static void main(String args[]){  

  15. Student s1=new Student(111,"ankit",5000f);  

  16. Student s2=new Student(112,"sumit",6000f);  

  17. s1.display();  

  18. s2.display();  

  19. }}  

Output:

111 ankit 5000

 

112 sumit 6000

It is better approach to use meaningful names for variables. So we use same name for instance variables and parameters in real time, and always use this keyword.

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example

this keyword

  1. class A{  

  2. void m(){System.out.println("hello m");}  

  3. void n(){  

  4. System.out.println("hello n");  

  5. //m();//same as this.m()  

  6. this.m();  

  7. }  

  8. }  

  9. class TestThis4{  

  10. public static void main(String args[]){  

  11. A a=new A();  

  12. a.n();  

  13. }}  

Output:

hello n

hello m

3) this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

  1. class A{  

  2. A(){System.out.println("hello a");}  

  3. A(int x){  

  4. this();  

  5. System.out.println(x);  

  6. }  

  7. }  

  8. class TestThis5{  

  9. public static void main(String args[]){  

  10. A a=new A(10);  

  11. }}  

Output:

hello a

10

Calling parameterized constructor from default constructor:

  1. class A{  

  2. A(){  

  3. this(5);  

  4. System.out.println("hello a");  

  5. }  

  6. A(int x){  

  7. System.out.println(x);  

  8. }  

  9. }  

  10. class TestThis6{  

  11. public static void main(String args[]){  

  12. A a=new A();  

  13. }}  

Output:

5

hello a

Real usage of this() constructor call

The this() constructor call should be used to reuse the constructor from the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this keyword.

  1. class Student{  

  2. int rollno;  

  3. String name,course;  

  4. float fee;  

  5. Student(int rollno,String name,String course){  

  6. this.rollno=rollno;  

  7. this.name=name;  

  8. this.course=course;  

  9. }  

  10. Student(int rollno,String name,String course,float fee){  

  11. this(rollno,name,course);//reusing constructor  

  12. this.fee=fee;  

  13. }  

  14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}  

  15. }  

  16. class TestThis7{  

  17. public static void main(String args[]){  

  18. Student s1=new Student(111,"ankit","java");  

  19. Student s2=new Student(112,"sumit","java",6000f);  

  20. s1.display();  

  21. s2.display();  

  22. }}  

Output:

111 ankit java null

112 sumit java 6000

Rule: Call to this() must be the first statement in constructor.

  1. class Student{  

  2. int rollno;  

  3. String name,course;  

  4. float fee;  

  5. Student(int rollno,String name,String course){  

  6. this.rollno=rollno;  

  7. this.name=name;  

  8. this.course=course;  

  9. }  

  10. Student(int rollno,String name,String course,float fee){  

  11. this.fee=fee;  

  12. this(rollno,name,course);//C.T.Error  

  13. }  

  14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}  

  15. }  

  16. class TestThis8{  

  17. public static void main(String args[]){  

  18. Student s1=new Student(111,"ankit","java");  

  19. Student s2=new Student(112,"sumit","java",6000f);  

  20. s1.display();  

  21. s2.display();  

  22. }}  


Compile Time Error: Call to this must be first statement in constructor

4) this: to pass as an argument in the method

The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example:

  1. class S2{  

  2.   void m(S2 obj){  

  3.   System.out.println("method is invoked");  

  4.   }  

  5.   void p(){  

  6.   m(this);  

  7.   }  

  8.   public static void main(String args[]){  

  9.   S2 s1 = new S2();  

  10.   s1.p();  

  11.   }  

  12. }  

Output:

method is invoked

Application of this that can be passed as an argument:

In event handling (or) in a situation where we have to provide reference of a class to another one. It is used to reuse one object in many methods.

5) this: to pass as argument in the constructor call

We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example:

  1. class B{  

  2.   A4 obj;  

  3.   B(A4 obj){  

  4.     this.obj=obj;  

  5.   }  

  6.   void display(){  

  7.     System.out.println(obj.data);//using data member of A4 class  

  8.   }  

  9. }  

  10.   

  11. class A4{  

  12.   int data=10;  

  13.   A4(){  

  14.    B b=new B(this);  

  15.    b.display();  

  16.   }  

  17.   public static void main(String args[]){  

  18.    A4 a=new A4();  

  19.   }  

  20. }  

Output:10

6) this keyword can be used to return current class instance

We can return this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement

  1. return_type method_name(){  

  2. return this;  

  3. }  

Example of this keyword that you return as a statement from the method

  1. class A{  

  2. A getA(){  

  3. return this;  

  4. }  

  5. void msg(){System.out.println("Hello java");}  

  6. }  

  7. class Test1{  

  8. public static void main(String args[]){  

  9. new A().getA().msg();  

  10. }  

  11. }  

Output:

Hello java

Proving this keyword

Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same.

  1. class A5{  

  2. void m(){  

  3. System.out.println(this);//prints same reference ID  

  4. }  

  5. public static void main(String args[]){  

  6. A5 obj=new A5();  

  7. System.out.println(obj);//prints the reference ID  

  8. obj.m();  

  9. }  

  10. }  

Output:

A5@22b3ea59

A5@22b3ea59

Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

  • For Method Overriding (so runtime polymorphism can be achieved).

  • For Code Reusability.

Syntax of Java Inheritance

  1. class Subclass-name extends Superclass-name  

  2. {  

  3.    //methods and fields  

  4. }  

The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called parent or super class and the new class is called child or subclass.

Java Inheritance Example

inheritance in java

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee.

  1. class Employee{  

  2.  float salary=40000;  

  3. }  

  4. class Programmer extends Employee{  

  5.  int bonus=10000;  

  6.  public static void main(String args[]){  

  7.    Programmer p=new Programmer();  

  8.    System.out.println("Programmer salary is:"+p.salary);  

  9.    System.out.println("Bonus of Programmer is:"+p.bonus);  

  10. }  

  11. }  

 Programmer salary is:40000.0

 Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.


Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.

types of inheritance in java

Note: Multiple inheritance is not supported in java through class.

When a class extends multiple classes i.e. known as multiple inheritance. For Example:

multiple inheritance in java


Single Inheritance Example

File: TestInheritance.java

  1. class Animal{  

  2. void eat(){System.out.println("eating...");}  

  3. }  

  4. class Dog extends Animal{  

  5. void bark(){System.out.println("barking...");}  

  6. }  

  7. class TestInheritance{  

  8. public static void main(String args[]){  

  9. Dog d=new Dog();  

  10. d.bark();  

  11. d.eat();  

  12. }}  

Output:

barking...

eating...

Multilevel Inheritance Example

File: TestInheritance2.java

  1. class Animal{  

  2. void eat(){System.out.println("eating...");}  

  3. }  

  4. class Dog extends Animal{  

  5. void bark(){System.out.println("barking...");}  

  6. }  

  7. class BabyDog extends Dog{  

  8. void weep(){System.out.println("weeping...");}  

  9. }  

  10. class TestInheritance2{  

  11. public static void main(String args[]){  

  12. BabyDog d=new BabyDog();  

  13. d.weep();  

  14. d.bark();  

  15. d.eat();  

  16. }}  

Output:

weeping...

barking...

eating...

Hierarchical Inheritance Example

File: TestInheritance3.java

  1. class Animal{  

  2. void eat(){System.out.println("eating...");}  

  3. }  

  4. class Dog extends Animal{  

  5. void bark(){System.out.println("barking...");}  

  6. }  

  7. class Cat extends Animal{  

  8. void meow(){System.out.println("meowing...");}  

  9. }  

  10. class TestInheritance3{  

  11. public static void main(String args[]){  

  12. Cat c=new Cat();  

  13. c.meow();  

  14. c.eat();  

  15. //c.bark();//C.T.Error  

  16. }}  

Output:

meowing...

eating...


Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.

  1. class A{  

  2. void msg(){System.out.println("Hello");}  

  3. }  

  4. class B{  

  5. void msg(){System.out.println("Welcome");}  

  6. }  

  7. class C extends A,B{//suppose if it were  

  8.    

  9.  Public Static void main(String args[]){  

  10.    C obj=new C();  

  11.    obj.msg();//Now which msg() method would be invoked?  

  12. }  

  13. }  


 Compile Time Error


What is polymorphism ?

Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations. I know it sounds confusing. Don’t worry we will discuss this in detail.

  • It is a feature that allows one interface to be used for a general class of actions.

  • An operation may exhibit different behavior in different instances.

  • The behavior depends on the types of data used in the operation.

  • It plays an important role in allowing objects having different internal structures to share the same external interface.

  • Polymorphism is extensively used in implementing inheritance.

Following concepts demonstrate different types of polymorphism in java.
1) Method Overloading
2) Method Overriding

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Rules for Method Overloading

  1. Overloading can take place in the same class or in its sub-class.

  2. Constructor in Java can be overloaded

  3. Overloaded methods must have a different argument list.

  4. Overloaded method should always be the part of the same class (can also take place in sub class), with same name but different parameters.

  5. The parameters may differ in their type or number, or in both.

  6. They may have the same or different return types.

  7. It is also known as compile time polymorphism.

Different ways to overload the method

There are two ways to overload the method in java

  1. By changing number of arguments

  2. By changing the data type

In java, Method Overloading is not possible by changing the return type of the method only.


1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling methods.

  1. class Adder{  

  2. static int add(int a,int b){return a+b;}  

  3. static int add(int a,int b,int c){return a+b+c;}  

  4. }  

  5. class TestOverloading1{  

  6. public static void main(String[] args){  

  7. System.out.println(Adder.add(11,11));  

  8. System.out.println(Adder.add(11,11,11));  

  9. }}  

Output:

22

33


2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.

  1. class Adder{  

  2. static int add(int a, int b){return a+b;}  

  3. static double add(double a, double b){return a+b;}  

  4. }  

  5. class TestOverloading2{  

  6. public static void main(String[] args){  

  7. System.out.println(Adder.add(11,11));  

  8. System.out.println(Adder.add(12.3,12.6));  

  9. }}  

Output:

22

24.9

Q) Why Method Overloading is not possible by changing the return type of method only?

In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let's see how ambiguity may occur:

  1. class Adder{  

  2. static int add(int a,int b){return a+b;}  

  3. static double add(int a,int b){return a+b;}  

  4. }  

  5. class TestOverloading3{  

  6. public static void main(String[] args){  

  7. System.out.println(Adder.add(11,11));//ambiguity  

  8. }}  

Output:

Compile Time Error: method add(int,int) is already defined in class Adder

System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be called?

Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time error if you declare the same method having same parameters.

Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let's see the simple example:

  1. class TestOverloading4{  

  2. public static void main(String[] args){System.out.println("main with String[]");}  

  3. public static void main(String args){System.out.println("main with String");}  

  4. public static void main(){System.out.println("main without args");}  

  5. }  

Output:

main with String[]

Method Overloading and Type Promotion

One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept by the figure given below:

method overloading with type promotion

As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float or double and so on.

 

 

Example of Method Overloading with TypePromotion

  1. class OverloadingCalculation1{  

  2.   void sum(int a,long b){System.out.println(a+b);}  

  3.   void sum(int a,int b,int c){System.out.println(a+b+c);}  

  4.   

  5.   public static void main(String args[]){  

  6.   OverloadingCalculation1 obj=new OverloadingCalculation1();  

  7.   obj.sum(20,20);//now second int literal will be promoted to long  

  8.   obj.sum(20,20,20);  

  9.   

  10.   }  

  11. }  


Output:40

       60


Example of Method Overloading with Type Promotion if matching found

If there are matching type arguments in the method, type promotion is not performed.

  1. class OverloadingCalculation2{  

  2.   void sum(int a,int b){System.out.println("int arg method invoked");}  

  3.   void sum(long a,long b){System.out.println("long arg method invoked");}  

  4.   

  5.   public static void main(String args[]){  

  6.   OverloadingCalculation2 obj=new OverloadingCalculation2();  

  7.   obj.sum(20,20);//now int arg sum() method gets invoked  

  8.   }  

  9. }  


Output:intarg method invoked

Example of Method Overloading with Type Promotion in case of ambiguity

If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity.

  1. class OverloadingCalculation3{  

  2.   void sum(int a,long b){System.out.println("a method invoked");}  

  3.   void sum(long a,int b){System.out.println("b method invoked");}  

  4.   

  5.   public static void main(String args[]){  

  6.   OverloadingCalculation3 obj=new OverloadingCalculation3();  

  7.   obj.sum(20,20);//now ambiguity  

  8.   }  

  9. }  


Output:Compile Time Error

 

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.

In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

  • Method overriding is used to provide specific implementation of a method that is already provided by its super class.

  • Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

  1. method must have same name as in the parent class

  2. method must have same parameter as in the parent class.

  3. must be IS-A relationship (inheritance).

Rules for Method Overriding:

  1. applies only to inherited methods

  2. object type (NOT reference variable type) determines which overridden method will be used at runtime

  3. Overriding method can have different return type 

  4. Overriding method must not have more restrictive access modifier

  5. Abstract methods must be overridden

  6. Static and final methods cannot be overridden

  7. Constructors cannot be overridden

  8. It is also known as Runtime polymorphism.

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.

  1. class Vehicle{  

  2.   void run(){System.out.println("Vehicle is running");}  

  3. }  

  4. class Bike extends Vehicle{  

  5.     

  6.   public static void main(String args[]){  

  7.   Bike obj = new Bike();  

  8.   obj.run();  

  9.   }  

  10. }  

Output:Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.

  1. class Vehicle{  

  2. void run(){System.out.println("Vehicle is running");}  

  3. }  

  4. class Bike2 extends Vehicle{  

  5. void run(){System.out.println("Bike is running safely");}  

  6.   

  7. public static void main(String args[]){  

  8. Bike2 obj = new Bike2();  

  9. obj.run();  

  10. }  

Output:Bike is running safely


Real example of Java Method Overriding

Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.

Java method overriding example of bank

  1. class Bank{  

  2. int getRateOfInterest(){return 0;}  

  3. }  

  4.   

  5. class SBI extends Bank{  

  6. int getRateOfInterest(){return 8;}  

  7. }  

  8.   

  9. class ICICI extends Bank{  

  10. int getRateOfInterest(){return 7;}  

  11. }  

  12. class AXIS extends Bank{  

  13. int getRateOfInterest(){return 9;}  

  14. }  

  15.   

  16. class Test2{  

  17. public static void main(String args[]){  

  18. SBI s=new SBI();  

  19. ICICI i=new ICICI();  

  20. AXIS a=new AXIS();  

  21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());  

  22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());  

  23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());  

  24. }  

  25. }  


Output:

SBI Rate of Interest: 8

ICICI Rate of Interest: 7

AXIS Rate of Interest: 9

Can we override static method?

No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.


Why we cannot override static method?

because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area.


Can we override java main method?

No, because main is a static method.

Difference between method Overloading and Method Overriding in java

There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below:

No.

Method Overloading

Method Overriding

1)

Method overloading is used to increase the readability of the program.

Method overriding is used to provide the specific implementation of the method that is already provided by its super class.

2)

Method overloading is performed within class.

Method overriding occurs in two classes that have IS-A (inheritance) relationship.

3)

In case of method overloading, parameter must be different.

In case of method overriding, parameter must be same.

4)

Method overloading is the example of compile time polymorphism.

Method overriding is the example of run time polymorphism.

5)

In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter.

Return type must be same or covariant in method overriding.

 

super keyword in java

The super keyword in java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.

Usage of java super Keyword

  1. super can be used to refer immediate parent class instance variable.

  2. super can be used to invoke immediate parent class method.

  3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields.

  1. class Animal{  

  2. String color="white";  

  3. }  

  4. class Dog extends Animal{  

  5. String color="black";  

  6. void printColor(){  

  7. System.out.println(color);//prints color of Dog class  

  8. System.out.println(super.color);//prints color of Animal class  

  9. }  

  10. }  

  11. class TestSuper1{  

  12. public static void main(String args[]){  

  13. Dog d=new Dog();  

  14. d.printColor();  

  15. }}  

Output:

black

white

In the above example, Animal and Dog both classes have a common property color. If we print color property, it will print the color of current class by default. To access the parent property, we need to use super keyword.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.

  1. class Animal{  

  2. void eat(){System.out.println("eating...");}  

  3. }  

  4. class Dog extends Animal{  

  5. void eat(){System.out.println("eating bread...");}  

  6. void bark(){System.out.println("barking...");}  

  7. void work(){  

  8. super.eat();  

  9. bark();  

  10. }  

  11. }  

  12. class TestSuper2{  

  13. public static void main(String args[]){  

  14. Dog d=new Dog();  

  15. d.work();  

  16. }}  


Output:

eating...

barking...

In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog class, it will call the eat() method of Dog class by default because priority is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:

  1. class Animal{  

  2. Animal(){System.out.println("animal is created");}  

  3. }  

  4. class Dog extends Animal{  

  5. Dog(){  

  6. super();  

  7. System.out.println("dog is created");  

  8. }  

  9. }  

  10. class TestSuper3{  

  11. public static void main(String args[]){  

  12. Dog d=new Dog();  

  13. }}  


Output:

animal is created

dog is created

Note: super() is added in each class constructor automatically by compiler if there is no super() or this().

java super

As we know well that default constructor is provided by compiler automatically if there is no constructor. But, it also adds super() as the first statement.

Another example of super keyword where super() is provided by the compiler implicitly.

  1. class Animal{  

  2. Animal(){System.out.println("animal is created");}  

  3. }  

  4. class Dog extends Animal{  

  5. Dog(){  

  6. System.out.println("dog is created");  

  7. }  

  8. }  

  9. class TestSuper4{  

  10. public static void main(String args[]){  

  11. Dog d=new Dog();  

  12. }}  

Output:

animal is created

dog is created

super example: real use

Let's see the real use of super keyword. Here, Emp class inherits Person class so all the properties of Person will be inherited to Emp by default. To initialize all the property, we are using parent class constructor from child class. In such way, we are reusing the parent class constructor.

  1. class Person{  

  2. int id;  

  3. String name;  

  4. Person(int id,String name){  

  5. this.id=id;  

  6. this.name=name;  

  7. }  

  8. }  

  9. class Emp extends Person{  

  10. float salary;  

  11. Emp(int id,String name,float salary){  

  12. super(id,name);//reusing parent constructor  

  13. this.salary=salary;  

  14. }  

  15. void display(){System.out.println(id+" "+name+" "+salary);}  

  16. }  

  17. class TestSuper5{  

  18. public static void main(String[] args){  

  19. Emp e1=new Emp(1,"ankit",45000f);  

  20. e1.display();  

  21. }}  

Output:

1 ankit 45000


Final Keyword in Java

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:

  1. variable

  2. method

  3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.

final keyword in java

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.

  1. class Bike9{  

  2.  final int speedlimit=90;//final variable  

  3.  void run(){  

  4.   speedlimit=400;  

  5.  }  

  6.  public static void main(String args[]){  

  7.  Bike9 obj=new  Bike9();  

  8.  obj.run();  

  9.  }  

  10. }//end of class  


Output:Compile Time Error


2) Java final method

If you make any method as final, you cannot override it.

Example of final method

  1. class Bike{  

  2.   final void run(){System.out.println("running");}  

  3. }  

  4.      

  5. class Honda extends Bike{  

  6.    void run(){System.out.println("running safely with 100kmph");}  

  7.      

  8.    public static void main(String args[]){  

  9.    Honda honda= new Honda();  

  10.    honda.run();  

  11.    }  

  12. }  

Output:Compile Time Error


3) Java final class

If you make any class as final, you cannot extend it.

Example of final class

  1. final class Bike{}  

  2.   

  3. class Honda1 extends Bike{  

  4.   void run(){System.out.println("running safely with 100kmph");}  

  5.     

  6.   public static void main(String args[]){  

  7.   Honda1 honda= new Honda();  

  8.   honda.run();  

  9.   }  

  10. }  

Output:Compile Time Error


Q) Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:

  1. class Bike{  

  2.   final void run(){System.out.println("running...");}  

  3. }  

  4. class Honda2 extends Bike{  

  5.    public static void main(String args[]){  

  6.     new Honda2().run();  

  7.    }  

  8. }  


Output:running...


Q) What is blank or uninitialized final variable?

A final variable that is not initialized at the time of declaration is known as blank final variable.

If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee.

It can be initialized only in constructor.

Example of blank final variable

  1. class Student{  

  2. int id;  

  3. String name;  

  4. final String PAN_CARD_NUMBER;  

  5. ...  

  6. }  

Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

  1. class Bike10{  

  2.   final int speedlimit;//blank final variable  

  3.     

  4.   Bike10(){  

  5.   speedlimit=70;  

  6.   System.out.println(speedlimit);  

  7.   }  

  8.   

  9.   public static void main(String args[]){  

  10.     new Bike10();  

  11.  }  

  12. }  


Output:70


static blank final variable

A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.

Example of static blank final variable

  1. class A{  

  2.   static final int data;//static blank final variable  

  3.   static{ data=50;}  

  4.   public static void main(String args[]){  

  5.     System.out.println(A.data);  

  6.  }  

  7. }  


Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.

  1. class Bike11{  

  2.   int cube(final int n){  

  3.    n=n+2;//can't be changed as n is final  

  4.    n*n*n;  

  5.   }  

  6.   public static void main(String args[]){  

  7.     Bike11 b=new Bike11();  

  8.     b.cube(5);  

  9.  }  

  10. }  


Output:Compile Time Error


Q) Can we declare a constructor final?

No, because constructor is never inherited.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

 

Ways to achieve Abstaction

There are two ways to achieve abstraction in java

  1. Abstract class (0 to 100%)

  2. Interface (100%)

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

Example abstract class

  1. abstract class A{}  


abstract method

A method that is declared as abstract and does not have implementation is known as abstract method.

Example abstract method

  1. abstract void printStatus();//no body and abstract  


Example of abstract class that has abstract method

In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.

  1. abstract class Bike{  

  2.   abstract void run();  

  3. }  

  4. class Honda4 extends Bike{  

  5. void run(){System.out.println("running safely..");}  

  6. public static void main(String args[]){  

  7.  Bike obj = new Honda4();  

  8.  obj.run();  

  9. }  

  10. }  


running safely..

Understanding the real scenario of abstract class

In this example, Shape is the abstract class, its implementation is provided by the Rectangle and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end user) and object of the implementation class is provided by the factory method.

factory method is the method that returns the instance of the class. We will learn about the factory method later.

In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked.

File: TestAbstraction1.java

  1. abstract class Shape{  

  2. abstract void draw();  

  3. }  

  4. //In real scenario, implementation is provided by others i.e. unknown by end user  

  5. class Rectangle extends Shape{  

  6. void draw(){System.out.println("drawing rectangle");}  

  7. }  

  8. class Circle1 extends Shape{  

  9. void draw(){System.out.println("drawing circle");}  

  10. }  

  11. //In real scenario, method is called by programmer or user  

  12. class TestAbstraction1{  

  13. public static void main(String args[]){  

  14. Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape() method  

  15. s.draw();  

  16. }  

  17. }  


drawing circle


 

Another example of abstract class in java

File: TestBank.java

  1. abstract class Bank{    

  2. abstract int getRateOfInterest();    

  3. }    

  4. class SBI extends Bank{    

  5. int getRateOfInterest(){return 7;}    

  6. }    

  7. class PNB extends Bank{    

  8. int getRateOfInterest(){return 8;}    

  9. }    

  10.     

  11. class TestBank{    

  12. public static void main(String args[]){    

  13. Bank b;  

  14. b=new SBI();  

  15. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    

  16. b=new PNB();  

  17. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    

  18. }}    


Rate of Interest is: 7 %

Rate of Interest is: 8 %


Abstract class having constructor, data member, methods etc.

An abstract class can have data member, abstract method, method body, constructor and even main() method.

File: TestAbstraction2.java

  1. //example of abstract class that have method body  

  2.  abstract class Bike{  

  3.    Bike(){System.out.println("bike is created");}  

  4.    abstract void run();  

  5.    void changeGear(){System.out.println("gear changed");}  

  6.  }  

  7.   

  8.  class Honda extends Bike{  

  9.  void run(){System.out.println("running safely..");}  

  10.  }  

  11.  class TestAbstraction2{  

  12.  public static void main(String args[]){  

  13.   Bike obj = new Honda();  

  14.   obj.run();  

  15.   obj.changeGear();  

  16.  }  

  17. }  


bike is created

running safely..

gear changed


Rule: If there is any abstract method in a class, that class must be abstract.

  1. class Bike12{  

  2. abstract void run();  

  3. }  


compile time error

Rule: If you are extending any abstract class that have abstract method, you must either provide the implementation of the method or make this class abstract.

Interface in Java

An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java.

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

  • It is used to achieve abstraction.

  • By interface, we can support the functionality of multiple inheritance.

  • It can be used to achieve loose coupling.

Java 8 Interface Improvement

Since Java 8, interface can have default and static methods which is discussed later.

Internal addition by compiler

The java compiler adds public and abstract keywords before the interface method. More, it adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and methods are public and abstract.

Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface.

Java Interface Example

In this example, Printable interface has only one method, its implementation is provided in the A class.

1. interface printable{  

2. void print();  

3. }  

4. class A6 implements printable{  

5. public void print(){System.out.println("Hello");}  

6.   

7. public static void main(String args[]){  

8. A6 obj = new A6();  

9. obj.print();  

10.  }  

11. }  


Output:

Hello

Java Interface Example: Drawable

In this example, Drawable interface has only one method. Its implementation is provided by Rectangle and Circle classes. In real scenario, interface is defined by someone but implementation is provided by different implementation providers. And, it is used by someone else. The implementation part is hidden by the user which uses the interface.

File: TestInterface1.java

1. //Interface declaration: by first user  

2. interface Drawable{  

3. void draw();  

4. }  

5. //Implementation: by second user  

6. class Rectangle implements Drawable{  

7. public void draw(){System.out.println("drawing rectangle");}  

8. }  

9. class Circle implements Drawable{  

10. public void draw(){System.out.println("drawing circle");}  

11. }  

12. //Using interface: by third user  

13. class TestInterface1{  

14. public static void main(String args[]){  

15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()  

16. d.draw();  

17. }}  

Output:

drawing circle

Java Interface Example: Bank

Let's see another example of java interface which provides the implementation of Bank interface.

File: TestInterface2.java

1. interface Bank{  

2. float rateOfInterest();  

3. }  

4. class SBI implements Bank{  

5. public float rateOfInterest(){return 9.15f;}  

6. }  

7. class PNB implements Bank{  

8. public float rateOfInterest(){return 9.7f;}  

9. }  

10. class TestInterface2{  

11. public static void main(String[] args){  

12. Bank b=new SBI();  

13. System.out.println("ROI: "+b.rateOfInterest());  

14. }}  

Output:

ROI: 9.15

 

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as multiple inheritance.

 

1. interface Printable{  

2. void print();  

3. }  

4. interface Showable{  

5. void show();  

6. }  

7. class A7 implements Printable,Showable{  

8. public void print(){System.out.println("Hello");}  

9. public void show(){System.out.println("Welcome");}  

10.   

11. public static void main(String args[]){  

12. A7 obj = new A7();  

13. obj.print();  

14. obj.show();  

15.  }  

16. }  

Output:Hello

       Welcome


Q) Multiple inheritance is not supported through class in java but it is possible by interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class because of ambiguity. But it is supported in case of interface because there is no ambiguity as implementation is provided by the implementation class. For example:

1. interface Printable{  

2. void print();  

3. }  

4. interface Showable{  

5. void print();  

6. }  

7.   

8. class TestInterface3 implements Printable, Showable{  

9. public void print(){System.out.println("Hello");}  

10. public static void main(String args[]){  

11. TestInterface3 obj = new TestInterface3();  

12. obj.print();  

13.  }  

14. }  


Output:

Hello

As you can see in the above example, Printable and Showable interface have same methods but its implementation is provided by class TestTnterface1, so there is no ambiguity.

 

Interface inheritance

A class implements interface but one interface extends another interface .

1. interface Printable{  

2. void print();  

3. }  

4. interface Showable extends Printable{  

5. void show();  

6. }  

7. class TestInterface4 implements Showable{  

8. public void print(){System.out.println("Hello");}  

9. public void show(){System.out.println("Welcome");}  

10.   

11. public static void main(String args[]){  

12. TestInterface4 obj = new TestInterface4();  

13. obj.print();  

14. obj.show();  

15.  }  

16. }  


Output:

Hello

Welcome

Java 8 Default Method in Interface

Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an example:

File: TestInterfaceDefault.java

1. interface Drawable{  

2. void draw();  

3. default void msg(){System.out.println("default method");}  

4. }  

5. class Rectangle implements Drawable{  

6. public void draw(){System.out.println("drawing rectangle");}  

7. }  

8. class TestInterfaceDefault{  

9. public static void main(String args[]){  

10. Drawable d=new Rectangle();  

11. d.draw();  

12. d.msg();  

13. }}  


Output:

drawing rectangle

default method

Java 8 Static Method in Interface

Since Java 8, we can have static method in interface. Let's see an example:

File: TestInterfaceStatic.java

1. interface Drawable{  

2. void draw();  

3. static int cube(int x){return x*x*x;}  

4. }  

5. class Rectangle implements Drawable{  

6. public void draw(){System.out.println("drawing rectangle");}  

7. }  

8.   

9. class TestInterfaceStatic{  

10. public static void main(String args[]){  

11. Drawable d=new Rectangle();  

12. d.draw();  

13. System.out.println(Drawable.cube(3));  

14. }}  


Output:

drawing rectangle

27

Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class

Interface

1) Abstract class can have abstract and non-abstract methods.

Interface can have only abstract methods. Since Java 8, it can have default and static methods also.

2) Abstract class doesn't support multiple inheritance.

Interface supports multiple inheritance.

3) Abstract class can have final, non-final, static and non-static variables.

Interface has only static and final variables.

4) Abstract class can provide the implementation of interface.

Interface can't provide the implementation of abstract class.

5) The abstract keyword is used to declare abstract class.

The interface keyword is used to declare interface.

6) Example:
public abstract class Shape{
public abstract void draw();
}

Example:
public interface Drawable{
void draw();
}

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).

Example of abstract class and interface in Java

Let's see a simple example where we are using interface and abstract class both.

  1. //Creating interface that has 4 methods  

  2. interface A{  

  3. void a();//bydefault, public and abstract  

  4. void b();  

  5. void c();  

  6. void d();  

  7. }  

  8.   

  9. //Creating abstract class that provides the implementation of one method of A interface  

  10. abstract class B implements A{  

  11. public void c(){System.out.println("I am C");}  

  12. }  

  13.   

  14. //Creating subclass of abstract class, now we need to provide the implementation of rest of the methods  

  15. class M extends B{  

  16. public void a(){System.out.println("I am a");}  

  17. public void b(){System.out.println("I am b");}  

  18. public void d(){System.out.println("I am d");}  

  19. }  

  20.   

  21. //Creating a test class that calls the methods of A interface  

  22. class Test5{  

  23. public static void main(String args[]){  

  24. A a=new M();  

  25. a.a();  

  26. a.b();  

  27. a.c();  

  28. a.d();  

  29. }}  


Output:

       I am a

       I am b

       I am c

       I am d


OOPS in Java OOPS in Java Reviewed by Asst. Prof. Sunita Rai on June 22, 2022 Rating: 5

No comments:

Powered by Blogger.