Search⌘ K

Solution Review: Override a Method using the Super Keyword

Explore how to override methods using the super keyword in Java to access base class methods within derived classes. Learn to enhance polymorphic behavior by appending base and derived class names for flexible code management.

We'll cover the following...

Solution

Java
// Base Class
class Shape {
// Private Data Members
private String name;
public Shape() { // Default Constructor
name = "Shape";
}
// Getter Function
public String getName() {
return name;
}
}
// Derived Class
class XShape extends Shape {
private String name;
public XShape(String name) { // Default Constructor
this.name = name;
}
// Overridden Method
public String getName() {
return super.getName() + ", " + this.name;
}
}
class Demo {
public static void main(String args[]) {
Shape circle = new XShape("Circle");
System.out.println(circle.getName());
}
}

Explanation

...