Prev
4. Object-Oriented Design and Principles
Next
6. Abstract classes and Interfaces

5. exercise: Inheritance and Encapsulation

  1. Review presentation Inheritance and Encapsulation

      

  2. Investigate jtm.activity05 package
  3. 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
  4. 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.

  5. 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.

  6. 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.

Prev
4. Object-Oriented Design and Principles
Next
6. Abstract classes and Interfaces
Tags:
Created by Valdis Vītoliņš on 2017-01-03 10:07
Last modified by Valdis Vītoliņš on 2019-09-22 23:40
 
Xwiki Powered
Creative Commons Attribution 3.0 Unported License