Huy Than
Huy Than

Reputation: 1546

Inheritance and polymorphism problems

I have this code form the book SCJP:

1.  class Mammal {
2.    String name = "furry ";
3.    String makeNoise() { return "generic noise"; }
4.  }
5.  
6.  class Zebra extends Mammal {
7.    String name = "stripes ";
8.    String makeNoise() { return "bray"; }
9.  }
10.
11. public class ZooKeeper {
12.   public static void main(String[] args) {
13.     new ZooKeeper().go();
14.   }
15.   
16.   void go() {
17.     Mammal m = new Zebra();
18.     System.out.println(m.name + m.makeNoise());
19.   }
20. }

The result from running this code is "furry bray".

Question 1

I don't understand why line 17 is not : Zebra zebra2 = new Zebra();

What is the purpose in each of the following cases, when to use which?

Mammal zebra1 = new Zebra();

vs

Zebra zebra2 = new Zebra();   

Question 2

Why is the variable name = "stripes" from the Zebra class overridden by the name = "furry" from the Mammal class? I expect the opposote: the variable from subclass will override that from superclass.

Upvotes: 2

Views: 807

Answers (3)

Dmitry Zaytsev
Dmitry Zaytsev

Reputation: 23952

  1. Because Zebra is Mammal

  2. Variables can't be overriden. If you change line 15 to:

    System.out.println(((Zebra) m).name + m.makeNoise());

    you'll get stripes bray

Upvotes: 1

roel
roel

Reputation: 2003

Answer 1: Depends on what you want. In this case it is not that obvious. But sometimes you just want an object to be off class 1 or class 2. imagine you have a method in zebra and not in mammal and you want tot use that method, then your object needs to be off class zebra and not mammal. But if there is a third-party class with a method only accepting mammal variables, then you must pass a mammal object.

Answer2: m.name is the variable of mammal (cannot be overridden) and m.makeNoise() is a method and this is overriden in Zebra.

Upvotes: 1

Ridcully
Ridcully

Reputation: 23655

Answer 1

Mammal zebra1 = new Zebra(); is used to show that you can assign objects of a derived class to variables of the parent class' type. That's also a reason for Mammal m, as you could also have a class Lion derived from Mammal and assign it to m. m can hold object of class Mammal or any class derived from Mammal.

Answer 2

This has also to do with inheritance. As you print out m.name, where m is a Mammal, you get the value of that property of the Mammal class. You cannot override variables by inheritance, only methods. If you'd add a method getName() to both of your classes where both would return name, m.getName() would return "stripes".

Upvotes: 6

Related Questions