Win a copy of Classic Computer Science Problems in Swift this week in the iOS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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.
 
Rancher
Posts: 3447
39
  • 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?
 
Ranch Foreman
Posts: 492
12
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
Ranch Foreman
Posts: 492
12
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: 58829
179
  • 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: 58829
179
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!