Results 1 to 2 of 2
Thread: Confused about Casts
- 01-17-2013, 06:56 PM #1
Member
- Join Date
- Oct 2012
- Posts
- 15
- Rep Power
- 0
Confused about Casts
Hi,
So right now I am learning about Casts and I am very confused and having difficulty understanding other definitions on google.
From what I understand, if we have 3 classes called Man, Boy, and Duck:
Object is the main superclass at the top of the hierarcy.
Man is a subclass of Object, and a superclass of Boy.
Duck is another subclass of Object.
So if we create a new instance variable referencing Boy of type Man:
Man aBoy = new Boy()
Then aBoy can only understand messages in the protocol of the Man class, and won't be able to understand any unique methods or messages defined in the Boy class because the variable is of type Man.
So basically does a cast mean that it will let us get around this, and by using a cast we can allow aBoy to access some of the methods in the Boy class even though it is of type Man (It's super class).
This is what I have got the impression of what a cast means or does so far but I think I might be wrong.
Am I also right in saying that a cast will only work on objects that are subtypes of its supertype? (even typing this sentence is confusing me but I hope I am making sense here).
- 01-17-2013, 09:38 PM #2
Re: Confused about Casts
One of the first things to get clear is that you cast references, not objects. Based on inheritance, every instance of a subtype is-a instance of any of its supertypes, all the way up to Object.
In your example, you have a reference of type Man which refers to an object/instance of type Boy. You can cast this reference to BoyThis cast succeeds without error only because the variable does refer to an instance of Boy. If that were not the case, then you would get a ClassCastException at runtime.Java Code:Boy boy = (Boy) aBoy;
The compiler is smart enough to not allow you to try casting references that are incompatible. In your examples, if you try to cast aBoy to Duckyou will get a compile error, because a Man reference can never refer to a Duck object/instance.Java Code:Duck duck = (Duck) aBoy;
And then there's casting between primitive types, which is an entirely different kettle of fish ...
dbWhy do they call it rush hour when nothing moves? - Robin Williams
Similar Threads
-
I'm so confused
By minabarnes in forum New To JavaReplies: 6Last Post: 01-14-2013, 04:16 AM -
So Confused
By Need Help in forum New To JavaReplies: 5Last Post: 03-04-2011, 06:18 PM -
Confused :?
By jESTPHROSTY in forum New To JavaReplies: 2Last Post: 10-17-2010, 07:38 PM -
Confused
By coldfire in forum New To JavaReplies: 3Last Post: 01-13-2009, 01:00 PM -
confused
By updev in forum AWT / SwingReplies: 6Last Post: 11-14-2008, 03:33 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks