This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
First: Isn't class Wolf supposed to extend class Canine? (In your code above it isn't explicitly extending anything).
Casting does not change the object or variable in any way. So a line like
does not do anything. Specifically, it's not going to convert the object that b refers to to a Canine.
The only thing a cast means, is that you tell the compiler "look, I have an object of type A here, and I want you to treat it as if it is type B - don't complain if you think it isn't a B". A check will still be done, but at runtime instead of compile time. If, at runtime, the object you're casting really is not a B, you'll get a ClassCastException.
no Wolf wasn't supposed to extend anything (well besides Object) the reason would come in a follow up question I was going to ask.
Will put it in netbeans and play around a bit more, was just seeing if someone had some sort of easy explanation to polymorphism and some general rules as no matter how many times I read up on it I get some questions wrong in the Enthuware mock exam regarding implications of polymorphism.
Joined: Sep 04, 2012
O I see what you mean with the cast, let me put it this way rather:
I think you should try making every class implement that Pet interface. Dog doesn’t need to say so explicitly, because its superclass already implements that interface. Then you can declare every object as of type Pet.
Wesleigh Pieters wrote:was just seeing if someone had some sort of easy explanation to polymorphism and some general rules
1. The effects of polymorphism are not particularly simple, so don't expect them to be.
2. The rules of polymorphism in Java are extremely simple: ALL methods are polymorphic unless they're declared final or static.
The simplest explanation I can give you is that every assignment in your TestClass can be thought of as:where:
VisibleType is the type determined by the compiler, and determines which methods you are allowed to call.
ActualType is the type determined by the JVM (ie, at runtime) and determines which version of a method actually gets run.
Specifically, given a call:the version run will be the lowest (most specific) implementation of method() at or above ActualType in the class hierarchy.
Isn't it funny how there's always time and money enough to do it WRONG?
Artlicles by Winston can be found here