This week's book giveaway is in the Open Source Projects forum.
We're giving away four copies of Spark in Action and have Jean-Georges Perrin on-line!
See this thread for details.
Win a copy of Spark in Action this week in the Open Source Projects forum!
  • 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
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Help me to understand this code.

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

i was expecting b why its print's c.
 
Rancher
Posts: 4603
47
  • 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: 508
15
Notepad Java
  • 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: 508
15
Notepad Java
  • 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: 69740
277
  • 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: 69740
277
  • 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.
 
You're not going crazy. You're going sane in a crazy word. Find comfort in this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic