File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question from the scjp book

 
in.anurag Singh
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It was from the Kathie Sierra SCJP 5 Study Guide.
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
in.anurag Singh
Greenhorn
Posts: 25
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 492
Firefox Browser Linux VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic