Skip to content
March 18, 2013 / Danii Oliver

Overriding – Object Oriented Analysis and Design

Overriding

Overriding Purpose to redefine a method that is in the superclass in order to have the subclass version be the one that runs.

  • Can only override public and protected.
  • CAN NOT be private, the subclass will not see it.
  • Return type must match and so must the signature.

If class Printer has a method Print(), the class Inkjet can’t output a better version of Print() if it is using the superclass defined Print() method.

If you want to make the Print() method better or different you would define your own Print() method in class Inkjet.
! →  Simply creating another method named print inside class Inkjet then creating an object pointer /reference Printer p = new Inkjet() then calling p.print(); will still call the class Printer’s Print() method.

class Output {

public doPrint(Printer p){

p.Print(); ← this does not happen by default to be the object type

}

}
*this is good because you will never have to change this code for any subclass of printer used

But if you override the Print() method in Inkjet and you point to an Inkjet
Class Printer {
//methods
public void print(){…}
}

Class Inkjet: Printer{
//methods
override public public void print(){…}
→ NO LONGER RECOGNIZES PRINTER’S PRINT(); ←
}
**Polymorphism will work in your favor here if you want the method in the subclass

How to get the method of the subclass?

Override – tells the compiler don’t pay attention to the type of reference PAY ATTENTION to the type of object!

  • Overriding needs two classes the Superclass and a Subclass.
  • The signatures need to be the same – name, arguments and return type.

**You can not override a PRIVATE method.
Overriding protected can only be used inside subclass. You cannot call a protected method in the outside class that instantiates an object of the subclass

The value of overriding is that you will be able to call the method of a subclass over the same method of it’s superclass

  • You want to do this if you are enhancing or changing the functionality of a subclass’s method.
  • Redefine = Override

Enhancing not Changing with private fields

Super
If you want to call the parent method and improve it you would call the super.Method
or base.Method

class Inkjet {
public void Print{

super.Print();

}

}
*Super means you don’t have to rewrite the original code that you still need.
*Here you are only calling one public or protected method from inside a superclass.

Flagging

Virtual
public virtual void Print() {…} → Flags the superclass method to be possibly overridden. You don’t have to override but you can if you want to. You must use the virtual keyword for Polymorphism to work.

Leave a comment