#
Superclass & Subclass in Java
#
Superclass & Subclass in Java - Theory
In Java OPP (Object-Oriented Programming) we speak about 4 main concepts:
Info
extends
is the keyword used to inherit the attributes and the methods of a class.
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
).
#
Superclass & Subclass in Java - Example
Here is an example of Java inheritance:
Shape.java
public class Shape {
public void drawShape1(){
System.out.println("Hello from drawShape1 !");
};
public void drawShape2(){
System.out.println("Hello from drawShape2 !");
};
}
Triangle.java
public class Triangle extends Shape {
void eraseShape() {
System.out.println("Hello from Triangle/eraseShape !");
}
// method OVERRIDING
@Override
public void drawShape2() {
System.out.println("Hello from Triangle/eraseShape2 !");
}
// method OVERLOADING
public void drawShape2(String par1) {
System.out.println("Hello "+par1+" from eraseShape2 !");
}
}
Info
When a class inherits the methods of another class it can override
& overload
these methods.
MainApp.java
public class MainApp {
public static void main(String [] args) {
Triangle triangle = new Triangle();
triangle.drawShape2();
triangle.drawShape2("Paris");
}
}
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.