#
Inheritance in Java
#
Inheritance in Java - theory
In Java OPP (Object-Oriented Programming) we speak about 4 main concepts:
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
This tutorial explains to you the concept of inheritance in Java.
Info
extends
is the keyword used to inherit the attributes/ variables and the methods of a class. The Constructors are not inherited (but can be called using super() keyword).- we can extend only a single class, and implement interfaces from many sources.
The pattern is like this:
class SuperClass {
//Some code here
}
class SubClass extends SuperClass {
//Some code here
}
The class which inherits the properties of other is known as subclass (child class) and the class whose properties
are inherited is known as superclass (parent class).
The subclass and superclass concepts are related to the super
keyword in Java.
When a class inherits the methods of another class it can override
& overload
these methods.
#
Inheritance in Java - Example
Here is an example of Java inheritance:
Shape.java
public class Shape {
public void drawShape(){
System.out.println("Draw shape from Shape Class.");
};
}
Triangle.java
public class Triangle extends Shape {
void eraseShape() {
System.out.println("Erase shape from Rectangle Class.");
}
}
MainApp.java
public class MainApp {
public static void main(String [] args) {
Triangle shape = new Triangle();
shape.drawShape();
shape.eraseShape();
}
}
As you can see in the Triangle class you can use drawShape() method defined in the Shape class. The same thing happens with the attributes (variables) of the class.
This is inheritance in Java.