开发者

Java Inheritance

开发者 https://www.devze.com 2023-03-04 04:11 出处:网络
A class C has a void method m with no parameters. Another class D extends C and overrides m. Each class has a constructor wi开发者_如何学Goth no parameters. In each of the following, say whether it is

A class C has a void method m with no parameters. Another class D extends C and overrides m. Each class has a constructor wi开发者_如何学Goth 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(); x.m();

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

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 Cs method will get called. If you object is of type D then Ds 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消