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();
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 ofmto 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 typeCthenCs method will get called. If you object is of typeDthenDs method will get called regardless of what type the reference is.The first answer:
is legal because and object of type
Dis aCas well (becauseDextendsC).The second answer:
is not legal because a reference to
Dcannot hold an object of its supertypeC.