Java Inheritance
Java class inheritance
In Java, Child class can inherit the properties and behaviour of ONLY ONE parent class.
class Rectangle extends the class Polygon. This is called inheritance
class Rectangle extends Polygon{
}
Java does not support multiple inheritance. That is, One class CAN NOT inherit more than one class. Java supports multi-level inheritance, meaning that one parent class can be extended by a class, which in turn can be extended by another class, and so on.
Java multi-level class inheritance
class Polygon implements Shape{
}
class Parallelogram extends Polygon{
}
class Rectangle extends Parallelogram {
}
class Square extends Rectangle{
}
In the above example, class Parallelogram extends Polygon. class Rectangle extends the class Parallelogram. class Square extends the class Rectangle
One interface can extend multiple interfaces
interface extends another interface using the keyword 'extends'.
interface Father{
}
interface Mother{
}
interface Child extends Father, Mother{
}
Classes and Interfaces - Relationship
A class can implement multiple interfaces
interface Animal{ ... } interface WaterAnimal extends Animal{ ... } interface LandBasedAnimal extends Animal{ ... } class Amphibian implements WaterAnimal, LandBasedAnimal{ ... }
A class can implement an interface. A class can extend another class. A class can extend one another class and implement multiple interfaces at the same time.
interface ScrollBar{
//some content...
}
interface StatusBar{
//some content...
}
interface ToolBar{
//some content...
}
interface PluginBar{
//some content...
}
class Window {
//some content...
}
class RichWindow extends Window implements ScrollBar, StatusBar, ToolBar, PluginBar{
//some content...
}
Inheritance - Diamond problem faced in Languages like C++
class D1{
int var1=10;
public void method1(){
}
}
class D2{
int var2=20;
public void method1(){
}
}
If class extends two classes D1 and D2, then arises a confusion on which among the two method1() would be inherited in the new class. This confusion is called the Diamond problem
In order to overcome the diamond problem, Java does not support multiple inheritance.
Java multiple inheritance
Java does NOT support multiple inheritance. In Java, if you want to have the properties and behaviours of two classes in a new class, Aggregation should be used
Example of using Aggregation instead of Inheritance
class A{
public void methodInA(){
}
}
class B{
public void methodInB(){
}
}
class C{
A aObj = new A();
B bObj = new B();
public static void main(){
C cObj = new C();
cObj.aObj.methodInA();
}
}