Note, that this recipe is not updated long time and could be outdated!
Got it.

5. Inheritance and Encapsulation

  1. Review presentation Inheritance and Encapsulation
  2. Review notes about practical exercise
  3. Investigate jtm.activity05 package
  4. Create class WaterRoad as a subclass of Road
    1. Select File — New — Class and enter:
    2. Name: WaterRoad
    3. Superclass: jtm.activity04.Road
    4. 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.

    5. Select Source — Override/Implement methods... and select method toString().
    6. Override .toString() method which returns string in form: WaterRoad From — To, 00km
  5. Create class Ship as a subclass of Transport
    1. Allow to store protected byte number of sails for Ship:
    2. Create Ship(String id, byte sails) constructor,
    3. Override move(Road) to return String in form:
      ID Ship is sailing on (Road as String) with x sails

      where:

      • (Road as String) is string representation of the road (without brackets),
      • x is actual number of sails.

      Note that fuel is not used when ship is moving, because it uses wind for sailing instead.

      return Cannot sail on (Road as String) if it is not WaterRoad.

  6. Create class Vehicle as subclass of Transport
    1. Allow to store protected int number of wheels for vehicle.
    2. Implement Vehicle(String id, float consumption, int tankSize, int wheels) constructor,
    3. Override method move(Road) for vehicle, which returns String in form:
      ID Vehicle is driving on (Road as String) with x wheels

      where:

      • (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.

  7. Implement Amphibia class in a such way, that it is a Transport:
    1. Make all internal properties of Amphibia private.
    2. Implement constructor Amphibia(String id, float consumption, int tankSize, byte sails, int wheels)
    3. Override move(Road road) method, that Amhibia behaves like a Vehicle on ground road and like a Ship on water road.

lightbulb Hints

  1. Use .getClass().getSimpleName() to get Type and reuse toString() of Road
  2. Use super(); to refer to parent class implementation of method or constructor.
  3. Use if(road instanceof WaterRoad) to check if object is type or sybtype of WaterRoad
  4. Use if(road.getClass() == Road.class) to check if object is exact type of Road class.

  

Created by Valdis Vītoliņš on 2017-01-03 08:07
Last modified by Valdis Vītoliņš on 2021-04-13 14:31
 
Xwiki Powered
Creative Commons Attribution 3.0 Unported License