• 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
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Help me to understand this code.  RSS feed

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

i was expecting b why its print's c.
 
Master Rancher
Posts: 3675
40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the key:


What class of object has been instantiated in this line?
 
Rancher
Posts: 506
15
Java Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A a = (B) new C();

Change the above statement to:

A a = new C();

Run the program and see what the result is.
 
Luanrkiran kumar
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know it's print c but what is the role of casting?

I thought Casted instance will override c
 
Prasad Saya
Rancher
Posts: 506
15
Java Notepad
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


In the above code snippet, both statements have the same meaning or result. The casting is an up casting.

There are concepts called down casting and method overriding you may want to get familiar with to understand whats happening with the code in your original post.
 
Marshal
Posts: 60780
190
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Luanrkiran kumar wrote:. . . but what is the role of casting?

To confuse you.

I thought Casted instance will override c

It obviously succeeded in confusing you.
 
Campbell Ritchie
Marshal
Posts: 60780
190
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Prasad Saya wrote:. . . The casting is an up casting. . . . .

Any cast towards a more generalised type will work, but have no effect, as long as it can be got to compile at all.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!