Inheritance is a mechanism through which a class can inherit properties(fields and methods) of another class. This allows to resuse the fields and methods of the parent class.
Inheritance also represents the IS-A relationship which describes the parent-child relationships between the classes.
Types of Inheritance
Java allows 5 types of Inheritance:
- Single - One class inherits another class.
class A {
public void method() {
// Do Something
}
}
class B extends A {
public void anotherMethod() {
// Do Something
}
}
- Multilevel - A chain of inheritance.
class A {
public void method() {
// Do Something
}
}
class B extends A {
public void anotherMethod() {
// Do Something
}
}
class C extends B {
public void yetAnotherMethod() {
// Do Something
}
}
- Hierarchical - Two or more classes inherit a class.
class A {
public void method() {
// Do Something
}
}
class B extends A {
public void anotherMethod() {
// Do Something
}
}
class C extends A {
public void yetAnotherMethod() {
// Do Something
}
}
- Multiple - A class inherits multiple interfaces. Java does not allow inheriting multiple classes as if the two parent classes have same name properties then there will be a conflict.
interface A {
public void interfaceMethod();
}
interface B {
public void interfaceMethod();
public void anotherInterfaceMethod();
}
class C implements A, B {
public void interfaceMethod() {
// Implementation of interfaceMethod
}
public void anotherInterfaceMethod() {
// Implementation of anotherInterfaceMethod
}
}
- Hybrid - Mix of Multiple and Hierarchical inheritance.
interface A {
public void interfaceMethod();
}
interface B extends A {
public void anotherInterfaceMethod();
}
interface C extends A {
public void yetAnotherInterfaceMethod();
}
class D implements B, C {
public void interfaceMethod() {
// Implementation of interfaceMethod
}
public void anotherInterfaceMethod() {
// Implementation of anotherInterfaceMethod
}
public void yetAnotherInterfaceMethod() {
// Implementation of yetAnotherInterfaceMethod
}
}