Results 1 to 2 of 2
Thread: Confused about Casts
- 01-17-2013, 07:56 PM #1Member
- Join Date
- Oct 2012
- Rep Power
Confused about Casts
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, 10: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 BoyJava 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 DuckJava Code:
Duck duck = (Duck) aBoy;
And then there's casting between primitive types, which is an entirely different kettle of fish ...
dbIf you're forever cleaning cobwebs, it's time to get rid of the spiders.
- By minabarnes in forum New To JavaReplies: 6Last Post: 01-14-2013, 05:16 AM
- By Need Help in forum New To JavaReplies: 5Last Post: 03-04-2011, 07:18 PM
- By jESTPHROSTY in forum New To JavaReplies: 2Last Post: 10-17-2010, 07:38 PM
- By coldfire in forum New To JavaReplies: 3Last Post: 01-13-2009, 02:00 PM
- By updev in forum AWT / SwingReplies: 6Last Post: 11-14-2008, 04:33 PM