Basically I’m having a little issue here.
I have a superclass and a subclass. I am supposed to do an assignment where I execute a method from the subclass, which overrides the method from the superclass. This works fine. The issue I am having is with “dynamic binding.” When I declare the reference variable type as of the same class as the subclass, it works fine. However, when I declare the type to be of the superclass, it does not recognize any of the subclass’s methods to even exist.
Here’s an example. I have a class called Ship and another subclass of Ship called BabyShip
If I declare a reference of ShippyShip as:
BabyShip subref = new BabyShip();
It works fine. However, when I declare it as:
Ship subref = new BabyShip();
The compiler doesn’t even recognize any of the methods from BabyShip if I declare the type of subref to be Ship… but my book clearly says that it should. Why is it doing this?
It gives a regular cannot find symbol error when I compile it.
ShipTester.java:8: error: cannot find symbol
ship.setMaxPassengers(1);
^
symbol: method setMaxPassengers(int)
location: variable ship of type Ship
1 error
Are you sure you’re not misreading the book? Java doesn’t do dynamic binding like this. If
setMaxPassengersis only declared inBabyShip, then the compiler is doing exactly the right thing. You can only access members which are known to the compile-time type of the expression you’re accessing them through – in this caseshipis of typeShip, so only the members ofShip(and its superclasses) are available.It’s hard to know exactly what the problem is without knowing exactly what the book says. The only sort of dynamic binding that occurs in normal Java is for overriding – if you’d declared
setMaxPassengersinShipbut then overridden it inBabyShip, then the overridden method would be called at execution time.Java 7 has some new features when it comes to dynamic binding, but it doesn’t sound like that’s what you’re talking about here.
If you can quote a specific bit of the book which you think implies this should work, please do so.