5. Inheritance and Encapsulation
Main steps
- Investigate jtm.activity05 package
- Create class WaterRoad as a subclass of Road
- Select File — New — Class and enter:
- Name: WaterRoad
- Superclass: jtm.activity04.Road
Select: Constructors from superclass, Inherited abstract methods and press Finish
Or, if you have not done it in class creation wizard: Select Source — Generate Constructors from Superclass..., select both constructors Road() and Road(String,String,int) and press OK.- Select Source — Override/Implement methods... and select method toString().
- Override .toString() method which returns string in form: WaterRoad From — To, 00km
- Create class Ship as a subclass of Transport
- Allow to store protected byte number of sails for Ship:
- Create Ship(String id, byte sails) constructor,
Override move(Road) to return String in form:
ID Ship is sailing on (Road as String) with x sailswhere:
- (Road as String) is string representation of the road (without brackets),
- x is actual number of sails.
return Cannot sail on (Road as String) if it is not WaterRoad.
- Create class Vehicle as subclass of Transport
- Allow to store protected int number of wheels for vehicle.
- Implement Vehicle(String id, float consumption, int tankSize, int wheels) constructor,
Override method move(Road) for vehicle, which returns String in form:
ID Vehicle is driving on (Road as String) with x wheelswhere:
- (Road as String) is string representation of the road,
- x is actual number of wheels.
return Cannot drive on (Road as String) if it is not Road.
- Implement Amphibia class in a such way, that it is a Transport:
- Make all internal properties of Amphibia private.
- Implement constructor Amphibia(String id, float consumption, int tankSize, byte sails, int wheels)
- Override move(Road road) method, that Amhibia behaves like a Vehicle on ground road and like a Ship on water road.
Hints
- Use .getClass().getSimpleName() to get Type and reuse toString() of Road
- Use super(); to refer to parent class implementation of method or constructor.
- Use if(road instanceof WaterRoad) to check if object is type or sybtype of WaterRoad
- Use if(road.getClass() == Road.class) to check if object is exact type of Road class.