Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Difference between casting and Superclass-Subclass referencing

 
Mohnish Khiani
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


What difference would be there in the working of o1 and o2 objects?
 
Andrey Kozhanov
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No difference. Both objects are of type A, containing instances of type B. Actually, casting 'new B()' to A does nothing, because 'B is-an A'.
 
Rob Spoor
Sheriff
Pie
Posts: 20497
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In fact, my Eclipse would give an "unnecessary cast" warning for line 12.
 
Mohnish Khiani
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That means whichever objects and instance variables can be accessed by o1 can also be accessed by o2....am I right?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15208
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, lines 11 and 12 do exactly the same, and o1 and o2 will behave exactly the same. The cast in line 12 is unnecessary, it's better to leave it out.
 
Mohnish Khiani
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okay,so is this also correct :

B obj=(B)(new A());
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15208
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, that line means something entirely different and will give you a ClassCastException when you try to run it.

It will be more clear if you give the classes more descriptive names than A and B. Consider this:

Now, you can ofcourse do this, because a Dog is an Animal, and a Cat is an Animal:

But the other way around doesn't work; an Animal is not always a Dog:

 
Mohnish Khiani
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you..I got it
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic