Topic – Abstract class – very important topic in Java.
Pre-requisite : Abstract method
Any method that does not have a body(open and closing curly
brace) instead ends with a semicolon is
called Abstract method.
Ex: public void display();
But how do you tell this to the compiler , very simple
Public abstract void display();
Abstract class – any class
in java which has at least one abstract method
must be declared as Abstract class.
public abstract class Employee {
Public abstract void display();
}
What happens if I don’t declare as Abstract in that case ?
Simple – compile time error.
Whenever we declare any
class as an abstract it means we cant instantiate that class.
Instantiate –creating an object for the class.
So Employee emp = new Employee(); - is wrong. Compile time
error.
So what is the use of abstract class if we are not able to
instantiate it ?
Answer is Polymorphism.
Polymorphism – methods which behaves differently in
different situations.
Any class which extends abstract class and implements all
the unimplemented methods of abstract
class becomes concrete class.
We can now store the object
of concrete class inside a reference variable of Abstract class.
Yes …got confused how
its polymorphism? Analyze the simple below program carefully.
package pack1;
import sun.security.action.GetLongAction;
abstract class Employee {
public abstract int getLeaves();
}
class
PermanentEmployee extends Employee{
static int leaves = 20;
public int getLeaves() {
return leaves;
}
}
class
ContractorEmployee extends Employee{
static int leaves = 10;
public int getLeaves() {
return leaves;
}
}
public class EmployeeMain{
public static void main(String[]
args) {
Employee
pEmp = new PermanentEmployee();
Employee
cEmp = new ContractorEmployee();
System.out.println("permanent
employee leaves");
System.out.println(pEmp.getLeaves());
System.out.println("Contractor
employee leaves");
System.out.println(cEmp.getLeaves());
}
}
so same method
getLeaves() behaves differently in different situations in the above program.
Both pEmp and cEmp are of type Employee and we are calling
getLeaves() method, but they are printing different values. How ?
Compiler looks at the type of a variable at the compile time but
at run time it looks for the variable content(ie where it is pointing).
Since here both pEmp and cEmp are both of type Employee at
compile time but at run time both are pointing to different objects.
This behavior is called polymorphism.
Quiz ??
1)can we declare class as an abstract if it does not contain
even a single abstract method ?
2)in the above program can we write like this
PermanentEmployee pEmp = new Employee ();
No comments:
Post a Comment