jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes Question from the scjp book Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question from the scjp book" Watch "Question from the scjp book" New topic
Author

Question from the scjp book

in.anurag Singh
Greenhorn

Joined: May 14, 2010
Posts: 25
Hi,
I came across a question, and was unable to understand the solution for the question.
Here it is..

Given:


Which statement(s), inserted at line 7, will compile? (Choose all that apply.)
A. Flower getType() { return this; }
B. String getType() { return "this"; }
C. Plant getType() { return this; }
D. Tulip getType() { return new Tulip(); }

The answer is A,C, and D.
and B is incorrect.

However i want to know WHY B is incorrect?
in.anurag Singh
Greenhorn

Joined: May 14, 2010
Posts: 25
It was from the Kathie Sierra SCJP 5 Study Guide.
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

Well flower extends from Plant right?
So Flower inherits all of the methods and attributes from Plants.
This means that Flower already has a getType() method and the the return signature of that method is type Plant not String.
So String getType() causes an error.

Sun has a good description of this here:
http://java.sun.com/docs/books/tutorial/java/IandI/override.html

Hunter


"If the facts don't fit the theory, get new facts" --Albert Einstein
in.anurag Singh
Greenhorn

Joined: May 14, 2010
Posts: 25
means,
A and D are correct because they declare and return sub-types of the Super Class Plant type.
C is correct because it is correctly overriding the method getType();
B is incorrect because it is returning "String" which is not a sub-type of Super Class Plant Type.

I want to know, If I am correct..
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

in.anurag Singh wrote:means,
A and D are correct because they declare and return sub-types of the Super Class Plant type.
C is correct because it is correctly overriding the method getType();
B is incorrect because it is returning "String" which is not a sub-type of Super Class Plant Type.

I want to know, If I am correct..


Does everything you typed here look correct to you? Does it compile when you try it?

Hunter
 
Consider Paul's rocket mass heater.
 
subject: Question from the scjp book
 
Similar Threads
About return type in JAVA
doubt -chapter 2 K& B -self test -q no 8
Doubt-Kathy Sierra
K&B doubt
Return type