Escolar Documentos
Profissional Documentos
Cultura Documentos
INHERITANCE
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent
object.
When you inherit from an existing class, you can reuse methods and fields of parent class.
Inheritance represents the ISA relationship, also known as parentchild relationship.
TYPES OF INHERITANCE
1. Single Inheritance
2. Multiple Inheritance (Through Interface)
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance (Through Interface)
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
Kamal Subramani
64
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispA() method of ClassA
b.dispA();
//call dispB() method of ClassB
b.dispB();
}
}
Output :
disp() method of ClassA
disp() method of ClassB
Kamal Subramani
65
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
Kamal Subramani
66
Output :
Kamal Subramani
67
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
b.dispA();
Kamal Subramani
68
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}
Output :
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA
Kamal Subramani