• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Junilu Lacar
  • Martin Vashko
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Scott Selikoff
  • salvin francis
  • Piet Souris

OCA Java SE 8 Programmer I Exam Guide by K. Sierra and B. Bates - Chapter 2, Q. 8, page 165

 
Mike Gualeni
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Following code in self test in the book:



I commented out the last line to run the program to see the result. But I was surprised that the output was "howl howl". I expected "howl woof". Why the casting to Dog in line 12 doesn't work? When I highlight the bark() method in my IDE in line 12, bark in line 2 is also highlighted?!
 
Campbell Ritchie
Marshal
Posts: 66525
251
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The declared type of ((Dog)new Hound(...)) might be Dog, but its runtime type is Hound. Overridden methods are called by their runtime type, even if you cast the reference. Dog doesn't have a sniff() method, so line 13 wouldn't have compiled.
 
Mike Gualeni
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank for your clear answer, and I knew that overridden methods are called by their runtime type. But new Hound() in line 12 doesn't has a ref type, or I can't see it? When I write

But I thought, if I cast the runtime type, it would be casted also?! But it isn't so?
When I cast a type then I only cast the ref type? The runtime type remains the same? Always?

Thanks.
 
Campbell Ritchie
Marshal
Posts: 66525
251
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Mike Gualeni wrote:Thank for . . .

That's a pleasure

if I cast the runtime type . . . The runtime type remains the same? Always?

Thanks.

Yes, it is always the same; it is the same as the class the object was created from. The same as you can infer from myObject.getClass().
 
No more fooling around. Read this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!