Inheritance
Inheritance
Inheritance
SIT Internal
Learning outcomes
• What is Inheritance
• Definition and code application
• Impact on Constructors
• Impact of Visibility modifiers
SIT Internal
What is inheritance?
Vehicle
SIT Internal
What is inheritance?
What is inheritance?
• Derive a new class from an existing one
Shirt Pants
- brand -brand
- size - size
- color - color
- sleeveLength - waistSize
- collorType - inSeamLength
SIT Internal
Shirt Pants
- brand - brand
- size - size
- color - color
- sleeveLength - waistSize
- collorType - inSeamLength
SIT Internal
Hierarchy of classes
ClothingItem
- brand Base class/Parent Class
- size
- color
Shirt
Pants
- sleeveLength
- collorType - waistSize
- inSeamLength
Vehicle
Root class
- fuel
Hierarchy of Classes
- noOfTires
+ drive()
Inheritance: Constructors
• Constructors are not inherited, even though they have public visibility
• parent's constructor are used to set up the "parent's part" of the object
• The first line of a child’s constructor should use the reference to call the
parent’s constructor
SIT Internal
Inheritance: Constructors
The super reference can be used
this.wheels = wheels;
System.out.println("Wheels: "+wheels);
}
SIT Internal
No error
public void setWheels(int wheels){
this.wheels = wheels;
System.out.println("Wheels: "+wheels);
}
SIT Internal
this.wheels = wheels;
System.out.println("Wheels: "+wheels);
}
SIT Internal
} Output:
}
Wheels: 5
SIT Internal
Visibility Modifiers
Modifier Class Subclass Package World
private
protected
public
SIT Internal
Conclude
• Derive a new class from an existing one allowing classes to inherit properties and behaviors from
other classes.
• It can also extend the functionality of the base class by adding new methods or fields to the child
class.
• It enables the creation of a hierarchy of classes
• Constructors are not inherited, but they are implicitly called
• By using access modifiers, you can control the level of visibility