Unit 3: Inheritance, Polymorphism, Encapsulation and Interfaces
Unit 3: Inheritance, Polymorphism, Encapsulation and Interfaces
Unit 3
Inheritance,
Polymorphism,
Encapsulation and
Interfaces
Introduction
In the previous unit, you were introduced to classes, objects
and class diagrams. In this unit, you are going to look into
more details about Inheritance, Polymorphism and
Encapsulation. You will also be introduced to a new concept
called Interface.
Success Criteria
By the end of this Unit, you should be able to:
Key Words
You will find the following key words or phrases in this unit:
extends, implements, interface. Watch for these and
make sure that you understand what they mean and how
they are used in the unit.
Inheritance
You may be interested to note that in unit 1, you were
introduced to inheritance. As already stated in the
previous unit, inheritance is defined as the process
where one class acquires the properties, methods and
fields of another. The class which inherits the
properties of other is known as subclass or derived
class or child class. The class whose properties are
inherited is known as superclass or base class or
parent class.
For example:
class Domcol{
.....
.....
}
class Nalikule extends Domcol{
.....
.....
}
class Vehicle {
protected String brand = "Ford"; //
Vehicle attribute
public void honk() { //
Vehicle method
System.out.println("Tuut, tuut!");
}
}
Types of Inheritance
1. Single Inheritance
In this type of inheritance, a class inherits
another class.
Example:
Animal class
Dog class
void bark()
{System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
2. Multilevel Inheritance
This occurs when there is a chain of inheritance.
Example:
Animal class
Dog class
BabyDog class
void weep()
{System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
3. Hierarchical Inheritance
This occurs when two or more classes inherit a
single class.
Example:
Animal class
Cow class
5. Hybrid Inheritance
Hybrid Inheritance is the combination of both
single and multiple inheritances.
Class A
Class C Class B
Class D
Polymorphism
Polymorphism means "many forms", and it occurs
when we have many classes that are related to each
other by inheritance.
class Animal {
public void animalSound() {
System.out.println("The animal makes a
sound");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); //
Create a Animal object
Animal myPig = new Pig(); // Create a
Pig object
Animal myDog = new Dog(); // Create a
Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
Encapsulation
You may wish to note that encapsulation was defined
in unit1 as a mechanism of wrapping the data
(variables) and code acting on the data (methods)
together as a single unit.
Benefits of Encapsulation
The fields of a class can be made read-only or
write-only.
A class can have total control over what is
stored in its fields.
Below is an example of encapsulation (Copy and paste
it in your IDE and run it):
return age;
}
public String getName() {
return name;
}
public String getIdNum() {
return idNum;
}
public void setAge( int newAge) {
age = newAge;
}
public void setName(String newName) {
name = newName;
}
public void setIdNum( String newId) {
idNum = newId;
}
}class RunEncapsulation {
public static void main(String args[]) {
Encapsulation encap = new
Encapsulation();
encap.setName("Madalitso");
encap.setAge(20);
encap.setIdNum("20 minutes");
System.out.print("Name : " +
encap.getName() + " Age : " + encap.getAge()+
" Running Time: " + encap.getIdNum());
}
}
Practise Activity
Suppose a class 'A' has a static method to print
"Parent". Its subclass 'B' also has a static method with
the same name to print "Child". Now call this method
by the objects of the two classes. Also, call this method
by an object of the parent class referring to the child
class i.e. A obj = new B().
Interfaces
For example:
// Interface
interface Animal {
public void animalSound(); // interface
method (does not have a body)
public void sleep(); // interface method
(does not have a body)
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig
object
myPig.animalSound();
myPig.sleep();
}
}
interface FirstInterface {
public void myMethod(); // interface method
}
interface SecondInterface {
public void myOtherMethod(); // interface
method
}
class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
Class Interface
Class Interface
Members of a class
All the members of
can be public,
the interface are
private, protected or
public by default.
default.
interface X
{
void methodX();
}
class Y implements X
{
void methodX()
{
System.out.println("Method X");
}
}
Practise Activity
Can you identify the error in the below code?
interface A
{
private int i;
}
Summary
In this Unit, you have been introduced to interfaces.
Implementations of polymorphism, encapsulation and
inheritance are also discussed.
• Interface is a group of related properties and methods
that describe an object, but neither provides
implementation nor initialization for them
• To inherit from a superclass, you need to use extends
keyword.
• Make sure that the class implements all of the
methods in the Interface
Reflection
Having gone through the unit, what can you say about
abstraction and interfaces?
Unit Test
1. Create a class 'Degree' having a method 'getDegree'
that prints "I got a degree". It has two subclasses
namely 'Undergraduate' and 'Postgraduate' each
having a method with the same name that prints "I
am an Undergraduate" and "I am a Postgraduate"
respectively. Call the method by creating an object of
each of the three classes.
2. Use this to answer the following question about
interfaces.
interface IVehicle {
// indicate how much a basic tune-up
costs
public double tuneUpCost();
// determine whether vehicle can hold
given num of passengers
public boolean canCarry(int
numPassengers);
}
class Car implements IVehicle {
int mileage;
int year;
int numDoors;
// constructor goes here
// indicate whether car was built before
given year
boolean builtBefore(int otherYear) {
return this.year < otherYear;
}
}
class Bicycle implements IVehicle {
int mileage;
int numGears;
// constructor goes here
}
class Ans{
public static void main(String[] args){
Undergraduate a = new Undergraduate();
Postgraduate b = new Postgraduate();
a.getDegree();
b.getDegree();
}
}