• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Working with inheritance

 
Serhat Duygun
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
im a beginner and trying to understand that how to reference variables to object. i gave the codes bellow my question is is there anyone explain to me how ?




 
Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the cast would work if the reference "g" holds a reference to Soccer object. But plain casts without instanceof checks are prone to error.
moreover if you can work with out adding the casts then its recommended.

You need not apply a cast in cases if the subclass overrides the method in the superclass then at runtime the jvm will pick the subclass/overridden version to execute. but in cases where the subclass overloads the method in superclass you need a reference which is of type subclass to actually invoke the overloaded version. But if you have an instance of Game class and then try to cast it to Soccer class, the cast would fail.

The above explanation is based on my assumption that "g" is of type Game. but the example you have provided is not sufficient and moreover you havent stated you query clearly.
 
Serhat Duygun
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry about not to be clear, it was a test question for 1Z0 803 you can see the question by click
 
Mohamed Sanaulla
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the Game g = new Soccer(): the "g" reference refers to a Soccer instance. But the "g" reference is of type Game and hence it will not be able to see the overloaded methods in Soccer class as reference to method binding happens at compile time and hence at compile time "g" is a Game. So you will not be able to invoke the overloaded play() method of the Soccer class. You might question that the actual instance is of Soccer, but the actual instance type is considered only when the method being invoked are overridden by the subclass.

Now coming back to Soccer s = (Soccer) g- this would work because the actual object/instance referred to by "g" is of Soccer type. And you must be able to invoke the overloaded version of the play() method as well as the overridden version of the play method.
 
Winston Gutkowski
Bartender
Pie
Posts: 10509
64
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Serhat Duygun wrote:Sorry about not to be clear, it was a test question for 1Z0 803...

For future reference, you can save us a lot of time if you QuoteYourSources (←click).

Winston
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic