5. Inheritance and encapsulation
- Review the presentation Inheritance and Encapsulation
- Explore the jtm.activity05 package
- Create the class WaterRoad as a subclass of Road.
- Choose File — New — Class and enter:
- Name: WaterRoad
- Superclass: jtm.activity04.Road
Select Constructors from superclass, Inherited abstract methods and press Finish
Or, if you haven't done so in the class creation wizard: select Source — Generate Constructors from Superclass..., select both constructors Road() and Road(String,String,int) and OK.- Choose Source — Override/Implement methods... and select the method toString().
- Replace the .toString() method, which returns a string in the following format: WaterRoad From — To, 00km
- Create the class Ship as a subclass of Transport.
- Create a protected byte field number of sails for the ship:
- Create a Ship(String id, byte sails) constructor,
Replace move(Road) so that it returns a string of the form:
ID Ship is sailing on (Road as String) with x sailswhere:
- (Road as String) is the string representation of the road (without the parentheses),
- x is the actual number of sails.
return Cannot sail on (Road as String) if it is not WaterRoad.
- Create a class Vehicle as a subclass of Transport.
- Create a protected int number of wheels field.
- Implement the Vehicle(String id, float consumption, int tankSize, int wheels) constructor,
Replace the move(Road)) method for the vehicle, which returns a string of the form:
ID Vehicle is driving on (Road as String) with x wheelswhere:
- (Road as String) is the string representation of the road,
- x is the actual number of wheels.
return Cannot drive on (Road as String) if it is not a Road.
- Implement the Amphibia class so that it is a subclass of Transport:
- Make all internal fields of Amphibia private.
- Create a constructor Amphibia(String id, float consumption, int tankSize, byte sails, int wheels)
- Replace the move(Road road) method so that the Amphibia behaves like a Vehicle on a land road and a Ship on a water road.
Tips
- Use .getClass().getSimpleName() to get the object type and reuse the Road.toString() method
- Use super(); to reference the parent class implementation of the method or constructor.
- Use if(road instanceof WaterRoad) to check if the object is a (sub)type of WaterRoad
- Use if(road.getClass() == Road.class) to check if the object is exactly Road type.