Inheritance


Inheritance is the process of writing a new class from existing class, the new class is called sub class and the existing class is called super class.
The ‘extends’ keyword is used to inherit the class. When one class extends another class all super class members become member of sub class except private member.
 Syntax:
Class super_class{
//variable and methods
}
class sub_class extends super_class{
//variable and method of super_class
//variable and methods of sub_class
}
Example:
class  super_class{
int a=10;
static int b=20;
{
System.out.println(“super-IB”);//instance block of super_class
}
static {
System.out.println(“super-SB”);//Static  block of super_class
}
void show_super(){
System.out.println(a);
System.out.println(b);

}
}
Class sub_class extends super_class{
int c=30;
static int d=40;
{
System.out.println(“sub-IB”);//instance block of sub_class
}
static{
System.out.println(“super-SB”);//static block of super_class
}
void show_sub(){
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);

}

}
class  Testing {
public static void main(String arg[]){
                             suber_class obj1=new super_class();
                             obj1.show_super();
                             suber_class obj2=new super_class();
                             obj2.show_super();
                             sub_class obj3=new sub_class();
                             obj3.show_sub();
                             obj3.show_super();       
                             obj3.show_sub();
sub_class obj4=new sub_class();
                             obj4.show_sub();
                             obj3.show_super();       
                             obj4.show_sub();
}
}

}
Output:
super-SB
super-IB
10
20
super-IB
10
20
sub-SB
super-IB
sub-IB
10
20
10
20
30
40
super-IB
sub-IB
10
20
10
20
30
40
Please try to understand the out of above program.
Note:
·         When JVM is trying to load subclass it check superclass and load the super class first and then subclass.
·         When you are creating object for the subclass first super class will be processed and then subclass.
In next post we will discuss  about type of Inhertance.

0 comments :

Post a Comment