Inheritance
- idea of a class “inheriting” properties from another class
Ex:
- Vehicle Class
- A car is a type of vehicle
- more of a “specialized vehicle”
- Bus
- color could be a unique factor
- Train
- Steam Engine Train
- Diesel Engine Train
- you have a basic model that basic features such as engine, or color that all vehicles can inherit
- Constructors are not inherited!
- Remember, constructors must be the name of the class, so if a constructor is “inherited”, its class and the constructor name will not be the same!
- they may have special features
Hiearchy is created in this example.
- Superclass will give everytrhing below in the hiearchy is refered to the subclass
Continued Example:
Class Vehicle:
- Name (String)
- make (String)
- model (String)
- Constructor: Vehicle (…)
- Method: moveForward()
Class Vehicle is the superclass of class Train
class Train:
- Name (String)
- make (String)
- model (String)
- Constructor: Train (…) //we would change this to Train instead of vehicle!
- Method: moveForward()
new addition:
- Conductor (String) //doesn’t carry to the vehicle class, conductor is a SUBCLASS of vehicle class
- moveFoward() method is still called the same thing, but we want to change the code inside it
- this is called overwriting!
- Overwriting: Changing the subclass body of a method that is inherited from a superclass
Class Train is the superclass of class DieselEngineTrain
class DieselEngineTrain:
- Name (String)
- make (String)
- model (String)
- Constructor: DiselEngineTrain: (…) //we would change this to DieselEngineTrain instead of Train!
- Method: moveForward() //inherit the overwritten method!
- Conductor (String)
new addition:
- oilLevel (double) //additional field added
//structure of example above
class Vehicle {
public String name;
public String make;
public String model;
public Vehicle(...) {
//implentation not shown
}
}
class Train extends Vehicle {
public String conductor;
public Train(...){
//implenatation not shown
}
public void moveFoward(){
//do something else
}
}
class DieselEngineTrain extends Train {
public double oilLevel;
public DieselEngineTrain(...){
//implementation not shown
}
}
//super(params) --> accesses the superclass's constructor
| public Vehicle(...) {
illegal start of type
| public Vehicle(...) {
<identifier> expected
- C
- C
- A
- A
- C
- D
- F
- D
- H //should be F
8/9