Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 18

Domasi College of Education

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:

 implement Inheritance, Polymorphism and


Encapsulation using Java
 define interface
 state differences between classes and interfaces
 implement interfaces using Java

Key Words
You will find the following key words or phrases in this unit:
extends, implements, interface. Watch for these and

Computer Programming II, Object-Oriented 3-0


Domasi College of Education

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.

To inherit from a superclass, you need to use extends


keyword.

For example:

class Domcol{
.....
.....
}
class Nalikule extends Domcol{
.....
.....
}

Copy the following code and run it in your IDE to


appreciate how inheritance works:

class Vehicle {
protected String brand = "Ford"; //
Vehicle attribute
public void honk() { //
Vehicle method
System.out.println("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang"; //
Car attribute

Computer Programming II, Object-Oriented 3-1


Domasi College of Education

public static void main(String[] args) {

// Create a myCar object


Car myCar = new Car();

// Call the honk() method (from the


Vehicle class) on the myCar object
myCar.honk();

// Display the value of the brand


attribute (from the Vehicle class) and the
value of the modelName from the Car class
System.out.println(myCar.brand + " " +
myCar.modelName);
}
}

The output of this program is:


Tuut, tuut!
Ford Mustang

Types of Inheritance
1. Single Inheritance
In this type of inheritance, a class inherits
another class.

Example:

Animal class

Dog class

In the above illustration, Dog class inherits the Animal


class, so there is the single inheritance.
Java code example showing single inheritance:
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{

Computer Programming II, Object-Oriented 3-2


Domasi College of Education

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

As you can see in the example given above, BabyDog


class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
Java code example showing multilevel inheritance:
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
}
class BabyDog extends Dog{

Computer Programming II, Object-Oriented 3-3


Domasi College of Education

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

Dog class Cat class

In the example given above, Dog and Cat classes


inherit the Animal class, so there is hierarchical
inheritance.
Java code example showing hierarchical inheritance:
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
}

Computer Programming II, Object-Oriented 3-4


Domasi College of Education

class Cat extends Animal{


void meow()
{System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat(); }
}
4. Multiple Inheritance
This occurs when one class extends more than
one class.
Example:

Cat class Dog class

Cow class

You should take note that in the example given above,


Cow class extends to Cat class and Dog class. Multiple
inheritances are not supported in Java through
classes.

5. Hybrid Inheritance
Hybrid Inheritance is the combination of both
single and multiple inheritances.

See the example below:

Class A

Class C Class B

Class D

Computer Programming II, Object-Oriented 3-5


Domasi College of Education

Hybrid inheritance is not supported in Java through


classes.

Polymorphism
Polymorphism means "many forms", and it occurs
when we have many classes that are related to each
other by inheritance.

Here is a Java code that demonstrates polymorphism:

class Animal {
public void animalSound() {
System.out.println("The animal makes a
sound");
}
}

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee
wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow
wow");
}
}

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();
}
}

Computer Programming II, Object-Oriented 3-6


Domasi College of Education

From the above code, notice that animalSound() is


called in all classes.

Why And When To Use "Inheritance" and


"Polymorphism"?

- It is useful for code reusability: reuse attributes and


methods of an existing class when you create a new
class.

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.

To achieve encapsulation in Java the following things


have to be done:
1. Declare the variables of a class as private.
2. Provide public setter and getter methods to
modify and view the variables values.
For more details about setter and getter methods, read
unit 4.

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):

public class Encapsulation{


private String name;
private String idNum;
private int age;
public int getAge() {

Computer Programming II, Object-Oriented 3-7


Domasi College of Education

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());
}
}

Computer Programming II, Object-Oriented 3-8


Domasi College of Education

Self-Evaluation Activity 3-a


1. What is the benefit of encapsulation in Java?
2. Which types of inheritances are not supported by Java
through classes?

Answers to this activity are at the end of the unit.

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().

Computer Programming II, Object-Oriented 3-9


Domasi College of Education

Interfaces

You should take note that Motto (n. d) defines an


interface as a “group of related properties and methods
that describe an object, but neither provides
implementation nor initialization for them” (para. 1).
An interface is an "abstract class" that is used to group
related methods with empty bodies.

Here is an example of an interface:

public interface Vehicle {


public String licensePlate = "";
public float maxVel;
public void start();
public void stop();
default void blowHorn(){
System.out.println("Blowing horn");
}
}

Notice that the above code contains two fields, two


methods, and a default method. Alone, it is not of
much use, but they are usually used along with
Classes. This is achieved by letting some class
implements it.

For example:

public class Car implements Vehicle {


public void start() {
System.out.println("starting
engine...");
}
public void stop() {
System.out.println("stopping
engine...");
}
}

As a rule, you must make sure that the class


implements all of the methods in the Interface. The
methods must have the exact same signature (name,
parameters and exceptions) as described in the
interface. The class does not need to declare the fields
though, only the methods.
Computer Programming II, Object-Oriented 3-10
Domasi College of Education

Another example (Copy and paste in your IDE and run


it):

// Interface
interface Animal {
public void animalSound(); // interface
method (does not have a body)
public void sleep(); // interface method
(does not have a body)
}

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided
here
System.out.println("The pig says: wee
wee");
}
public void sleep() {
// The body of sleep() is provided here
System.out.println("Zzz");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig
object
myPig.animalSound();
myPig.sleep();
}
}

Some of the important points you must know about


interfaces:
 Interface methods do not have a body - the body
is provided by the "implement" class
 On implementation of an interface, you must
override all of its methods
 Interface methods are by default abstract and
public
 Interface attributes are by default public, static
and final

Computer Programming II, Object-Oriented 3-11


Domasi College of Education

 An interface cannot contain a constructor (as it


cannot be used to create objects)

As a reminder, in this unit, you have learned that


multiple inheritances are not supported through Java
classes. However, with interfaces, multiple
inheritances are possible.

Look at this example (Copy and paste in your IDE and


run it):

interface FirstInterface {
public void myMethod(); // interface method
}

interface SecondInterface {
public void myOtherMethod(); // interface
method
}

class DemoClass implements FirstInterface,


SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}

class Main {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}

Differences between Classes and Interfaces

Shri (2018) identifies the following differences:

Class Interface

 A class describes the  An interface


attributes and contains behaviors

Computer Programming II, Object-Oriented 3-12


Domasi College of Education

Class Interface

behaviors of an that a class


object. implements.

 A class may contain  An interface


abstract methods, contains only
concrete methods. abstract methods.

 Members of a class
 All the members of
can be public,
the interface are
private, protected or
public by default.
default.

Self Evaluation Activity 3-b


1. Define interface
2. State any two differences between classes and interfaces
3. Why the below code is showing compile time error?

interface X
{
void methodX();
}
class Y implements X
{
void methodX()
{
System.out.println("Method X");
}
}

Answers to this activity are at the end of the unit.

Computer Programming II, Object-Oriented 3-13


Domasi College of Education

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?

Computer Programming II, Object-Oriented 3-14


Domasi College of Education

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
  }

a. What methods do you need to add to each of


Car and Bicycle to get this code fragment to
compile (setting aside the missing
constructors)?

Computer Programming II, Object-Oriented 3-15


Domasi College of Education

b. Does having a class implement an interface


change how you write its constructor?
c. Should builtBefore be added to the IVehicle
interface? Why or why not?

Answers to Unit 3 Activities


Answers to Activity 3-a
1. Choose any one:
a. The fields of a class can be made read-only or
write-only.
b. A class can have total control over what is
stored in its fields.
2. Multiple and Hybrid inheritances

Answers to Unit 3 Activities


Answers to Activity 3-b
1. A group of related properties and methods that
describe an object, but neither provides
implementation nor initialization for them.
2. Choose any two:
• A class describes the attributes and
behaviours of an object while an interface
contains behaviours that a class
implements.
• A class may contain abstract methods,
concrete methods while an interface
contains only abstract methods.
• Members of a class can be public, private,
protected or default while all the members
of the interface are public by default.

Computer Programming II, Object-Oriented 3-16


Domasi College of Education

3. Interface methods must be implemented as public.


Because, interface methods are public by default and
you should not reduce the visibility of any methods
while overriding.

Answers to Unit 3 Test


1. Here is the solution:
class Degree{
public void getDegree(){
System.out.println("I got a degree");
}
}

class Undergraduate extends Degree{


public void getDegree(){
System.out.println("I am an Undergraduate");
}
}

class Postgraduate extends Degree{


public void getDegree(){
System.out.println("I am a Postgraduate");
}
}

class Ans{
public static void main(String[] args){
Undergraduate a = new Undergraduate();
Postgraduate b = new Postgraduate();
a.getDegree();
b.getDegree();
}
}

2. Here are the solutions:


a. The two methods listed in the interface
(tuneUpCost and canCarry).
b. No. Interfaces affect what method you must
provide in a class, but they do not impact the
constructors.
c. No. Only methods that make sense for all classes
that implement the interface should be included
in the interface. builtBefore is not meaningful
for bicycles (since they have no information about
when they were built).

Computer Programming II, Object-Oriented 3-17

You might also like