Odo.lv » Java Bootcamp » 5. Inheritance and Encapsulation

Atpakaļ
4. Object-Oriented Design and Principles
Tālāk
6. Abstract classes and Interfaces

5. exercise: Inheritance and Encapsulation

  1. Review presentation Inheritance and Encapsulation
  2. Investigate org.activity05 package
  3. Create class WaterRoad as a subclass of Road
    1. Select File — New — Class and enter:
    2. Name: WaterRoad
    3. Superclass: org.activity04.Road
    4. Select: Constructors from seperclass, Inherited abstract methods
    5. Press Finish
    6. Select Source — Generate Constructors from Superclass..., select both constructors Road() and Road(String,String,int) and press OK.
    7. Select Source — Override/Implement methods... and select method toString().
    8. 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 private 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 WaterRoad From — To, 00km with x sails
      where x is actual number of sails,
      return Cannot sail on (Road representation as String) if it is not WaterRoad.

  5. Create class Vehicle as subclass of Transport
    1. Allow to store private 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 From — To, 00km with x wheels
      where x is actual number of wheels,
      return Cannot drive on (Road representation 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.

Atpakaļ
4. Object-Oriented Design and Principles
Tālāk
6. Abstract classes and Interfaces
Tagi:
Izveidojis Valdis Vītoliņš 2017-01-03 12:07
Pēdējais mainījis Valdis Vītoliņš 2017-03-08 10:26

Xwiki Powered
Creative Commons Attribution 3.0 Unported License