comparter
comparter

Reputation: 23

Why overriding a method of superclass, instead of giving it a different name?

I have the following code example:

class Primate {
   public void sayType() {
      System.out.println("I'm a Primate");
   }
}

class Human extends Primate {
   public void sayType() {
      System.out.println("I'm a Human!");
   }
}
public class TalkingPrimates {

   public static void main(String args[]) {
      Primate a = new Primate();
      Primate b = new Human();

      a.sayType(); 
      b.sayType(); 
   }
}

which should output:

I'm a Primate
I'm a Human!

Why can't I just name the sayType method to humanHello for example, and avoid messing with @Override and confusing later? I'm a newbie, and taken this example somewhere else, so maybe there are more complicated usages for it that you will show me

(Another thing - the line Primate b = new Human(), is it what called "Dynamic method dispatch"?)

Upvotes: 0

Views: 84

Answers (2)

Murat Karagöz
Murat Karagöz

Reputation: 37594

If you do as you say then you could not take advantage of Polymorphism e.g.

for(Primate p : primateList){
  p.sayType(); // 
}

With that you can let the Objects do the implementation of your pre-defined method name and be sure that it's always the same name.

Upvotes: 4

Bathsheba
Bathsheba

Reputation: 234685

Well, you could, but then Primate b = new Human(); b.sayType(); would output "I'm a primate". Furthermore, you would not be able to access humanHello via a reference to a Primate, unless you took a nasty reference cast, which would fail if the reference was not referring to a Human instance.

Overriding is useful if you have a container of references to primates (humans, gibbons, etc.), and you want to access the correct method through a particular reference.

Upvotes: 1

Related Questions