Overriding in Inheritance
suggest changeOverriding in inheritance is used when a subclass provides its own version of a method already defined in a superclass. Overriding allows the user to reuse code by using existing material and modifying it to suit the user’s needs better.
The following example demonstrates how ClassB overrides the functionality of ClassA by changing what gets sent out through the printing method. The fragment is not a complete compilation unit: main has to be inside a class.
Example:
public static void main(String[] args) {
ClassA a = new ClassA();
ClassA b = new ClassB();
a.printing();
b.printing();
}
class ClassA {
public void printing() {
System.out.println("A");
}
}
class ClassB extends ClassA {
public void printing() {
System.out.println("B");
}
}
Output:
A
B
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents