|
One of the most effective concepts of OOPs is because it provides the hierarichical classifications and we can create a general class and can be inherited by other classes.
The class which is inherited as defined as “ Super Class” and other classes which inherit the super class is called “Sub class”. A subclass is a specialized version of a Superclass which inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements.
Java provides us a keyword “Extends” which helps the super class to be inherited by the other sub class.
The following program creates a superclass called A and a subclass called B. Notice how the keyword extends is used to create a subclass of A.
public class InheritanceExample {
public static void main(String[] args) {
B b = new B();
// showij is not defined in class B
// but in class A and still class B
// is able to call it. This is
// called inheritence.
b.showij();
b.showk();
b.sum();
}
}
class A {
int i = 3;
int j = 5;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Class B is a subclass of Class A.
class B extends A {
int k = 10;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i + j + k));
}
}
|