Derived Class Methods that Override Base Class Methods

Contact Us or call 1-877-932-8228
Derived Class Methods that Override Base Class Methods

Derived Class Methods that Override Base Class Methods

As we saw before, you can create a method in the derived class with the same name as a base class method. Note that:

  • The new method overrides (and hides) the original method.
  • You can still call the base class method from within the derived class if necessary, by adding the super keyword and a dot in front of the method name.
  • The base class version of the method is not available to outside code.
  • You can view the super term as providing a reference to the base class object buried inside the derived class.
  • You cannot do super.super. to back up two levels.
  • You cannot change the return type when overriding a method, since this would make polymorphism impossible.

Example: a revised MyDerived using super.show()

class MyDerived extends MyBase {
	int y;
	public MyDerived(int x) {
		super(x);
	} 
	public MyDerived(int x, int y) {
		super(x);
		this.y = y;
	}
	public int getY() {
		return y;
	} 
	public void show() {
		super.show();
		System.out.println("y = " + y);
	}
}

Use of super to call a base class version of an overridden method

Next