简体   繁体   中英

Java Inheritance

A class C has a void method m with no parameters. Another class D extends C and overrides m. Each class has a constructor with no parameters. In each of the following, say whether it is legal, and if so, which definition of m will be used.

i) C x = new D(); xm(); C x = new D(); xm();

ii) D x = new C(); xm(); D x = new C(); xm();

I think i is legal, and ii is not illegal. Not sure how I get my head around this question, any hints are welcome.

The best way to answer the question is to write some code and see what happens. Use System.out.println("method called from C"); in your implementation of m to tell which implementation is called. Having said that, the whole point of overriding a method is so that the new implementation will get used. If you object is of type C then C s method will get called. If you object is of type D then D s method will get called regardless of what type the reference is.

The first answer:

C x = new D();

is legal because and object of type D is a C as well (because D extends C ).

The second answer:

D x = new C();

is not legal because a reference to D cannot hold an object of its supertype C .

Yes, you are right.

(i) is legal, and it will be D 's m method that gets run (this is called polymorphism ).

(ii) is illegal, and will not even compile, because D is not a supertype of C (in fact, it's a subtype). We could make it compile by writing it as:

D x = (D) new C(); x.m();

but then it would fail at runtime with a ClassCastException

Try to think of inheritance in terms of "is a" relationships.

If D extends C then that means each D is a C, but does not imply that each C is a D.

To apply that thinking, translate the question into an "is a" question.

C x = new D()

is a statement that requires that a new D() is a C .

In String s = new Object() , ask yourself "is a new Object() a String ?" What about vice-versa?

Good luck learning OOP.

i) is legal, ii) is not. It's very easy to see if you use a metaphor, say class C is Animal and class D is Dog, method m() is makeNoise. Now it's legal to have a variable of class Animal and assign a Dog to it (because a dog "is a" animal), but it's not legal to instantiate an Animal and assign it to Dog since the Dog is more specific than Animal (we can not say an animal "is a" dog).

Now for the method: the method is always called on the runtime type, not on the variable type (all method calls are so-called virtual in Java), so in case i) it calls the m() method of class D, not of class C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM