Java Technology - 2018 - OOPS Concept

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

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

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.

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.

Object and Class in Java

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

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

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 Re-usability
  • 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.

What are the different ways to create an object in Java?

There are many ways to create an object in java. They are:
  • By new keyword
  • By newInstance() method
  • By clone() method
  • By deserialization
  • By factory method etc.
class Account{  
int acc_no;  
String name;  
float amount;  
void insert(int a,String n,float amt){  
acc_no=a;  
name=n;  
amount=amt;  
}  
void deposit(float amt){  
amount=amount+amt;  
System.out.println(amt+" deposited");  
}  
void withdraw(float amt){  
if(amount<amt){  
System.out.println("Insufficient Balance");  
}else{  
amount=amount-amt;  
System.out.println(amt+" withdrawn");  
}  
}  
void checkBalance(){System.out.println("Balance is: "+amount);}  
void display(){System.out.println(acc_no+" "+name+" "+amount);}  
}  
  
class TestAccount{  
public static void main(String[] args){  
Account a1=new Account();  
a1.insert(832345,"Ankit",1000);  
a1.display();  
a1.checkBalance();  
a1.deposit(40000);  
a1.checkBalance();  
a1.withdraw(15000);  
a1.checkBalance();  
}}   

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.
class Bike1{  
Bike1(){System.out.println("Bike is created");}  
public static void main(String args[]){  
Bike1 b=new Bike1();  
}
}
default constructor
Rule: If there is no constructor in a class, compiler automatically creates a 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.

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.

class Student4{  
    int id;  
    String name;
   
    Student4(int i,String n){  
    id = i;
    name = n;
    }
    void display(){System.out.println(id+" "+name);}  
 
    public static void main(String args[]){  
    Student4 s1 = new Student4(111,"Karan");  
    Student4 s2 = new Student4(222,"Aryan");  
    s1.display();
    s2.display();
   }
}

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.

class Student5{  
    int id;  
    String name;
    int age;  
    Student5(int i,String n){  
    id = i;
    name = n;
    }
    Student5(int i,String n,int a){  
    id = i;
    name = n;
    age=a;
    }
    void display(){System.out.println(id+" "+name+" "+age);}  
 
    public static void main(String args[]){  
    Student5 s1 = new Student5(111,"Karan");  
    Student5 s2 = new Student5(222,"Aryan",25);  
    s1.display();
    s2.display();
   }
}

Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in java

There are many differences between constructors and methods. They are given below.
Java ConstructorJava 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
class Student6{  
    int id;  
    String name;  
    Student6(int i,String n){  
    id = i;  
    name = n;  
    }  
      
    Student6(Student6 s){  
    id = s.id;  
    name =s.name;  
    }  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    Student6 s1 = new Student6(111,"Karan");  
    Student6 s2 = new Student6(s1);  
    s1.display();  
    s2.display();  
   }  
}  

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.
class Student7{  
    int id;  
    String name;  
    Student7(int i,String n){  
    id = i;  
    name = n;  
    }  
    Student7(){}  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    Student7 s1 = new Student7(111,"Karan");  
    Student7 s2 = new Student7();  
    s2.id=s1.id;  
    s2.name=s1.name;  
    s1.display();  
    s2.display();  
   }  
}  

Q) Does constructor return any value?

Ans:yes, that is current class instance (You cannot use return type yet it returns a value.
This is an implicit event. If you do not create constructor, the program will create default
constructor internally.).

class demo
{
demo{}
}
class demo1
{
public static void main(String as[])
{
demo d = new demo();
System.out.println(d);
}
}
output: demo@7d4991ad it is the reference id of the object 'd' of class demo which is returned
 by the constructor. if u will not define your constructor then jvm will get this id from default
constructor.
you can cross check it by this line: System.out.println(new demo()); output: demo@1b6d3586.
 since every object has its separate heap area in memory so reference id of each object also
vary.

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 rather 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


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

class Student9{
int rollno;
String name;
static String college = "ITS";

static void change(){
college = "BBDIT";
}

Student9(int r, String n){
rollno = r;
name = n;
}

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

public static void main(String args[]){
Student9.change();

Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");

s1.display();
s2.display();
s3.display();
}
}

Output:111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT



Another example of static method that performs normal calculation
//Program to get cube of a given number by static method

class Calculate{
static int cube(int x){
return x*x*x;
}

public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}

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


The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.


this and super cannot be used in static context.

class A{
int a=40;//non static

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

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

class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}

Output:static block is invoked 
 Hello main

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

No from JDK 1.7
Before it was possible using Static block.

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.

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.

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword.

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.

class Student{  
int rollno;  
String name;  
float fee;  
Student(int rollno,String name,float fee){  
this.rollno=rollno;  
this.name=name;  
this.fee=fee;  
}  
void display(){System.out.println(rollno+" "+name+" "+fee);}  
}  
  
class TestThis2{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  

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

class Student{  
int rollno;  
String name,course;  
float fee;  
Student(int rollno,String name,String course){  
this.rollno=rollno;  
this.name=name;  
this.course=course;  
}  
Student(int rollno,String name,String course,float fee){  
this.fee=fee;  
this(rollno,name,course);//C.T.Error  
}  
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}  
}  
class TestThis8{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit","java");  
Student s2=new Student(112,"sumit","java",6000f);  
s1.display();  
s2.display();  
}}

  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. }}  
111 ankit java null
112 sumit java 6000

this keyword can be used to return current class instance

class A{   A getA(){   return this;   }   void msg(){System.out.println("Hello java");}   }   class Test1{   public static void main(String args[]){   new A().getA().msg();   }   }  

Inheritance in Java

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 in java is a
mechanism in which one object acquires all the properties and behaviors of parent object.
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
Note: Multiple inheritance is not supported in java through class.
types of inheritance in java




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

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.


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.
java method overloading

Advantage of method overloading

Method overloading increases the readability of the program.

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.
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. }}  

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. }}  

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. }}  

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

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

method overloading with type promotion

class OverloadingCalculation1{  
  void sum(int a,long b){System.out.println(a+b);}  
  void sum(int a,int b,int c){System.out.println(a+b+c);}  
  
  public static void main(String args[]){  
  OverloadingCalculation1 obj=new OverloadingCalculation1();  
  obj.sum(20,20);//now second int literal will be promoted to long  
  obj.sum(20,20,20);  
  
  }  
}

class OverloadingCalculation1{  
  void sum(int a, int b){System.out.println(a+b);}  
  void sum(int a,int b,int c){System.out.println(a+b+c);}  
  
  public static void main(String args[]){  
  OverloadingCalculation1 obj=new OverloadingCalculation1();  
  obj.sum(20,'a');//now second int literal will be promoted to long  
  obj.sum(20,20,20);  
  
  }  
}
Output: 117

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).
class Vehicle{  
void run(){System.out.println("Vehicle is running");}  
}  
class Bike2 extends Vehicle{  
void run(){System.out.println("Bike is running safely");}  
  
public static void main(String args[]){  
Bike2 obj = new Bike2();  
obj.run();  
}  

Java method overriding example of bank

Can we override static method?

No, static method cannot be overridden.

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 OverloadingMethod 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. }}  

 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. }}  


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. }}  

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. }}  

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. }}  

Instance initializer block 

Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created.
The initialization of the instance variable can be directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.

Example of instance initializer block

Let's see the simple example of instance initializer block the performs initialization.
  1. class Bike7{  
  2.     int speed;  
  3.       
  4.     Bike7(){System.out.println("speed is "+speed);}  
  5.    
  6.     {speed=100;}  
  7.        
  8.     public static void main(String args[]){  
  9.     Bike7 b1=new Bike7();  
  10.     Bike7 b2=new Bike7();  
  11.     }      
  12. }  
Output:speed is 100
       speed is 100
 
There are three places in java where you can perform operations:
  1. method
  2. constructor
  3. block


What is invoked first, instance initializer block or constructor?

  1. class Bike8{  
  2.     int speed;  
  3.       
  4.     Bike8(){System.out.println("constructor is invoked");}  
  5.    
  6.     {System.out.println("instance initializer block invoked");}  
  7.        
  8.     public static void main(String args[]){  
  9.     Bike8 b1=new Bike8();  
  10.     Bike8 b2=new Bike8();  
  11.     }      
  12. }  
Output:instance initializer block invoked
       constructor is invoked
       instance initializer block invoked
       constructor is invoked

Note: The java compiler copies the code of instance initializer block in every constructor.

instance initializer block

Rules for instance initializer block :

There are mainly three rules for the instance initializer block. They are as follows:
  1. The instance initializer block is created when instance of the class is created.
  2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
  3. The instance initializer block comes in the order in which they appear.

Program of instance initializer block that is invoked after super()

  1. class A{  
  2. A(){  
  3. System.out.println("parent class constructor invoked");  
  4. }  
  5. }  
  6. class B2 extends A{  
  7. B2(){  
  8. super();  
  9. System.out.println("child class constructor invoked");  
  10. }  
  11.   
  12. {System.out.println("instance initializer block is invoked");}  
  13.   
  14. public static void main(String args[]){  
  15. B2 b=new B2();  
  16. }  
  17. }  

Output:parent class constructor invoked
       instance initializer block is invoked
       child class constructor invoked

Another example of instance block

  1. class A{  
  2. A(){  
  3. System.out.println("parent class constructor invoked");  
  4. }  
  5. }  
  6.   
  7. class B3 extends A{  
  8. B3(){  
  9. super();  
  10. System.out.println("child class constructor invoked");  
  11. }  
  12.   
  13. B3(int a){  
  14. super();  
  15. System.out.println("child class constructor invoked "+a);  
  16. }  
  17.   
  18. {System.out.println("instance initializer block is invoked");}  
  19.   
  20. public static void main(String args[]){  
  21. B3 b1=new B3();  
  22. B3 b2=new B3(10);  
  23. }  
  24. }  
Output:parent class constructor invoked
       instance initializer block is invoked
       child class constructor invoked
       parent class constructor invoked
       instance initializer block is invoked
       child class constructor invoked 10

We can put code in a constructor or a method or an initialization block. What is the
 use of initialization block? Is it necessary that every java program must have it?
First of all, there are two types of initialization blocks:
  • instance initialization blocks, and
  • static initialization blocks.
This code should illustrate the use of them and in which order they are executed:
public class Test {

    static int staticVariable;
    int nonStaticVariable;        

    // Static initialization block:
    // Runs once (when the class is initialized)
    static {
        System.out.println("Static initalization.");
        staticVariable = 5;
    }

    // Instance initialization block:
    // Runs each time you instantiate an object
    {
        System.out.println("Instance initialization.");
        nonStaticVariable = 7;
    }

    public Test() {
        System.out.println("Constructor.");
    }

    public static void main(String[] args) {
        new Test();
        new Test();
    }
}
Prints:
Static initalization.
Instance initialization.
Constructor.
Instance initialization.
Constructor.
Instance itialization blocks are useful if you want to have some code run regardless of which 
constructor is used or if you want to do some instance initialization for anonymous classes.
Order of execution:
  1. static initialization blocks of super classes
  2. static initialization blocks of the class
  3. instance initialization blocks of super classes
  4. constructors of super classes
  5. instance initialization blocks of the class
  6. constructor of the class.
A couple of additional points to keep in mind :
  1. The code in static initialization block will be executed at class load time (and yes, that means only once per class load), before any instances of the class are constructed and before any static methods are called.
  2. The instance initialization block is actually copied by the Java compiler into every constructor the class has. So every time the code in instance initialization block is executed exactly before the code in constructor.
public class StaticTest extends parent {
    static {
        System.out.println("inside satic block");
    }

    StaticTest() {
        System.out.println("inside constructor of child");
    }

    {
        System.out.println("inside initialization block");
    }

    public static void main(String[] args) {
        new StaticTest();
        new StaticTest();
        System.out.println("inside main");
    }
}

class parent {
    static {
        System.out.println("inside parent Static block");
    }
    {
        System.out.println("inside parent initialisation block");
    }

    parent() {
        System.out.println("inside parent constructor");
    }
}
this gives
inside parent Static block
inside satic block
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside main
its like stating the obvious but seems a little more clear.
import java.io.*;
public class GFG
{
    // Initializer block starts..
    {
        // This code is executed before every constructor.
        System.out.println("Common part of constructors invoked !!");
    }
    // Initializer block ends
    public GFG()
    {
        System.out.println("Default Constructor invoked");
    }
    public GFG(int x)
    {
        System.out.println("Parametrized constructor invoked");
    }
    public static void main(String arr[])
    {
        GFG obj1, obj2;
        obj1 = new GFG();
        obj2 = new GFG(0);
    }
}
Output:
Common part of constructors invoked!!
Default Constructor invoked
Common part of constructors invoked!!
Parametrized constructor invoked 

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. 

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
class Bike9{    final int speedlimit=90;//final variable    void run(){     speedlimit=400;    }    public static void main(String args[]){    Bike9 obj=new  Bike9();    obj.run();    }   }//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 Honda1();  
  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.

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.

Polymorphism in Java

Polymorphism in java is a concept by which we can perform a single action by different
 ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly"
 means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and
 runtime polymorphism. We can perform polymorphism in java by method overloading
and method overriding. If you overload static method in java, it is the example of
compile time polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a
call to an overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a
 superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.Let's first understand the upcasting before Runtime
Polymorphism.

Upcasting

When reference variable of Parent class refers to the object of Child class, it is known as
 upcasting. For example:

Upcasting in java

  1. class A{}  
  2. class B extends A{}  
  1. A a=new B();//upcasting  


Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike
 class and overrides its run() method. We are calling the run method by the reference
 variable of Parent class. Since it refers to the subclass object and subclass method overrides
 the Parent class method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime
 polymorphism.

  1. class Bike{  
  2.   void run(){System.out.println("running");}  
  3. }  
  4. class Splender extends Bike{  
  5.   void run(){System.out.println("running safely with 60km");}  
  6.   
  7.   public static void main(String args[]){  
  8.     Bike b = new Splender();//upcasting  
  9.     b.run();  
  10.   }  
  11. }  
Output:running safely with 60km.

Java Runtime Polymorphism Example: Bank

Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks are providing 8.4%, 7.3% and 9.7% rate of interest.
Java Runtime Polymorphism example of bank


  1. class Bank{  
  2. float getRateOfInterest(){return 0;}  
  3. }  
  4. class SBI extends Bank{  
  5. float getRateOfInterest(){return 8.4f;}  
  6. }  
  7. class ICICI extends Bank{  
  8. float getRateOfInterest(){return 7.3f;}  
  9. }  
  10. class AXIS extends Bank{  
  11. float getRateOfInterest(){return 9.7f;}  
  12. }  
  13. class TestPolymorphism{  
  14. public static void main(String args[]){  
  15. Bank b;  
  16. b=new SBI();  
  17. System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());  
  18. b=new ICICI();  
  19. System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());  
  20. b=new AXIS();  
  21. System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());  
  22. }  
  23. }  
Output:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Java Runtime Polymorphism Example: Shape

  1. class Shape{  
  2. void draw(){System.out.println("drawing...");}  
  3. }  
  4. class Rectangle extends Shape{  
  5. void draw(){System.out.println("drawing rectangle...");}  
  6. }  
  7. class Circle extends Shape{  
  8. void draw(){System.out.println("drawing circle...");}  
  9. }  
  10. class Triangle extends Shape{  
  11. void draw(){System.out.println("drawing triangle...");}  
  12. }  
  13. class TestPolymorphism2{  
  14. public static void main(String args[]){  
  15. Shape s;  
  16. s=new Rectangle();  
  17. s.draw();  
  18. s=new Circle();  
  19. s.draw();  
  20. s=new Triangle();  
  21. s.draw();  
  22. }  
  23. }  
Output:
drawing rectangle...
drawing circle...
drawing triangle...

Java Runtime Polymorphism Example: Animal

  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. }  
  7. class Cat extends Animal{  
  8. void eat(){System.out.println("eating rat...");}  
  9. }  
  10. class Lion extends Animal{  
  11. void eat(){System.out.println("eating meat...");}  
  12. }  
  13. class TestPolymorphism3{  
  14. public static void main(String[] args){  
  15. Animal a;  
  16. a=new Dog();  
  17. a.eat();  
  18. a=new Cat();  
  19. a.eat();  
  20. a=new Lion();  
  21. a.eat();  
  22. }}  
Output:
eating bread...
eating rat...
eating meat...

Java Runtime Polymorphism with Data Member

Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data members.
In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.

Rule: Runtime polymorphism can't be achieved by data members.

  1. class Bike{  
  2.  int speedlimit=90;  
  3. }  
  4. class Honda3 extends Bike{  
  5.  int speedlimit=150;  
  6.   
  7.  public static void main(String args[]){  
  8.   Bike obj=new Honda3();  
  9.   System.out.println(obj.speedlimit);//90  
  10. }  
Output:
90

Java Runtime Polymorphism with Multilevel Inheritance

Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
  1. class Animal{  
  2. void eat(){System.out.println("eating");}  
  3. }  
  4. class Dog extends Animal{  
  5. void eat(){System.out.println("eating fruits");}  
  6. }  
  7. class BabyDog extends Dog{  
  8. void eat(){System.out.println("drinking milk");}  
  9. public static void main(String args[]){  
  10. Animal a1,a2,a3;  
  11. a1=new Animal();  
  12. a2=new Dog();  
  13. a3=new BabyDog();  
  14. a1.eat();  
  15. a2.eat();  
  16. a3.eat();  
  17. }  
  18. }  
Output:
eating
eating fruits
drinking Milk

Try for Output

  1. class Animal{  
  2. void eat(){System.out.println("animal is eating...");}  
  3. }  
  4. class Dog extends Animal{  
  5. void eat(){System.out.println("dog is eating...");}  
  6. }  
  7. class BabyDog1 extends Dog{  
  8. public static void main(String args[]){  
  9. Animal a=new BabyDog1();  
  10. a.eat();  
  11. }}  
Output:
Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.






Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.
There are two types of binding
  1. static binding (also known as early binding).
  2. dynamic binding (also known as late binding).

static binding

When type of the object is determined at compiled time(by the compiler), it is known as static
 binding. If there is any private, final or static method in a class, there is static binding.

Example of static binding

  1. class Dog{  
  2.  private void eat(){System.out.println("dog is eating...");}  
  3.   
  4.  public static void main(String args[]){  
  5.   Dog d1=new Dog();  
  6.   d1.eat();  
  7.  }  
  8. }  

Dynamic binding

When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding

  1. class Animal{  
  2.  void eat(){System.out.println("animal is eating...");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6.  void eat(){System.out.println("dog is eating...");}  
  7.   
  8.  public static void main(String args[]){  
  9.   Animal a=new Dog();  
  10.   a.eat();  
  11.  }  
  12. }  
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the
instance of Dog is also an instance of Animal.So compiler doesn't know its type, only its
 base type.

Static Vs. Dynamic Binding in Java

Here are few important difference between static and dynamic binding
1) Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime.
2) private, final and static methods and variables uses static binding and bonded by compiler while virtual methods are bonded during runtime based upon runtime object.
3) Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding.
3) Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.
Here is an example which will help you to understand both static and dynamic binding in Java.
Static Binding Example in Java
public class StaticBindingTest  
{  
 public static void main(String args[])  
   {
     Collection c = new HashSet();
     StaticBindingTest et = new StaticBindingTest();
     et.sort(c);
   }
   //overloaded method takes Collection argument
  public Collection sort(Collection c)
   {
    System.out.println("Inside Collection sort method");
    return c;
   }
  //another overloaded method which takes HashSet argument which is sub class
  public Collection sort(HashSet hs)
  {
    System.out.println("Inside HashSet sort method");
    return hs;
   }
}
Output: Inside Collection sort method
Example of Dynamic Binding in Java
public class DynamicBindingTest 
{
 public static void main(String args[]) 
  {
    Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
    vehicle.start();       //Car's start called because start() is overridden method
  }
}

class Vehicle 
  {
    public void start() 
      {
           System.out.println("Inside start method of Vehicle");
      }
  }
class Car extends Vehicle 
  {
    @Override
    public void start() 
     {
       System.out.println("Inside start method of Car");
     }
}
Output: Inside start method of Car

Java instanceof

The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the
 instance with type. It returns either true or false. If we apply the instanceof operator with
 any variable that has null value, it returns false.
Let's see the simple example of instance operator where it tests the current class.
  1. class Simple1{  
  2.  public static void main(String args[]){  
  3.  Simple1 s=new Simple1();  
  4.  System.out.println(s instanceof Simple1);//true  
  5.  }  
  6. }  

Another example of java instanceof operator

  1. class Animal{}  
  2. class Dog1 extends Animal{//Dog inherits Animal  
  3.   
  4.  public static void main(String args[]){  
  5.  Dog1 d=new Dog1();  
  6.  System.out.println(d instanceof Animal);//true  
  7.  }  
  8. }  

class Dog2{  
 public static void main(String args[]){  
  Dog2 d=null;  
  System.out.println(d instanceof Dog2);//false  
 }  
}  

Abstract class in Java

A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).

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 Abstraction

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..

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

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.

class Bike12{  
abstract void run();  
} //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.


Note: If you are beginner to java, learn interface first and skip this example.

  1. interface A{  
  2. void a();  
  3. void b();  
  4. void c();  
  5. void d();  
  6. }  
  7.   
  8. abstract class B implements A{  
  9. public void c(){System.out.println("I am c");}  
  10. }  
  11.   
  12. class M extends B{  
  13. public void a(){System.out.println("I am a");}  
  14. public void b(){System.out.println("I am b");}  
  15. public void d(){System.out.println("I am d");}  
  16. }  
  17.   
  18. class Test5{  
  19. public static void main(String args[]){  
  20. A a=new M();  
  21. a.a();  
  22. a.b();  
  23. a.c();  
  24. a.d();  
  25. }}  
Output:I am a
       I am b
       I am c
       I am d

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.

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

interface in java

In other words, Interface fields are public, static and final by default, and methods are public and
 abstract.
relationship between class and interface
 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. }  

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

 multiple inheritance in java

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. }  

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. }}  

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. }}  

Q) What is marker or tagged interface?

An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.
  1. //How Serializable interface is written?  
  2. public interface Serializable{  
  3. }  

Nested Interface in Java

Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in the nested classes chapter. For example:
  1. interface printable{  
  2.  void print();  
  3.  interface MessagePrintable{  
  4.    void msg();  
  5.  }  
  6. }  

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 classInterface
1) Abstract class can have abstract and non-abstractmethods.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. }}  










Comments

Popular posts from this blog

Jersey JAX RS Jar

Tomcat Installation Steps for Windows & add tomcat to eclipse

REST API