permaculture playing cards*
The moose likes Java in General and the fly likes Difference between casting and Superclass-Subclass referencing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Difference between casting and Superclass-Subclass referencing" Watch "Difference between casting and Superclass-Subclass referencing" New topic
Author

Difference between casting and Superclass-Subclass referencing

Mohnish Khiani
Ranch Hand

Joined: May 17, 2010
Posts: 65


What difference would be there in the working of o1 and o2 objects?
Andrey Kozhanov
Ranch Hand

Joined: Mar 12, 2010
Posts: 79
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

Joined: Oct 27, 2005
Posts: 19651
    
  18

In fact, my Eclipse would give an "unnecessary cast" warning for line 12.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Mohnish Khiani
Ranch Hand

Joined: May 17, 2010
Posts: 65
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

Joined: Aug 16, 2005
Posts: 14074
    
  16

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Mohnish Khiani
Ranch Hand

Joined: May 17, 2010
Posts: 65
okay,so is this also correct :

B obj=(B)(new A());
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

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

Joined: May 17, 2010
Posts: 65
thank you..I got it
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Difference between casting and Superclass-Subclass referencing
 
Similar Threads
Equals and ==
Regarding instanceof operator
Question about polymorphism and casting
islands of isolation(Garbage Collection)
Accessing private variable