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).
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 Boy
This 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.
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 Duck
you will get a compile error, because a Man reference can never refer to a Duck object/instance.
Duck duck = (Duck) aBoy;
And then there's casting between primitive types, which is an entirely different kettle of fish ...