You are on page 1of 36

DCIT 201- PROGRAMMING I

Session 3 – Inheritance , Polymorphism and Interfaces

Lecturer: Mr. Paul Ammah, CSD


Contact Information: pammah@ug.edu.gh

Department of Computer Science


School of Physical and Mathematical Science
Session Objectives
• Understand inheritance, polymorphism and interfaces
• Be able to implement subclasses that inherit and override
superclass methods
• Be able to work with interface types
• Understand the role of inheritance to produce windowing
interfaces within Java application programs

Slide 2
Session Outline
The key topics to be covered in the session are as follows:
• Superclasses and Subclasses
• Polymorphism
• Interface types

Slide 3
Reading List
• Chapter 11 - Introduction to Java Programming(Liang, 2011)
• Chapter 9 - Big Java Late Objects (Horstmann, 2012)

Slide 4
Topic One

SUPERCLASSES AND SUBCLASSES

Slide 5
Introduction
• Object-oriented programming allows you to derive new
classes from existing classes. This is called inheritance.
• Inheritance is an important and powerful feature in Java for
reusing software.
• Inheritance enables you to define a general class and later
extend it to more specialized classes.
• The specialized classes inherit the properties and methods
from the general class.

Slide 6
Superclass and subclass
• In Java terminology, a class C1 extended from another class
C2 is called a subclass, and C2 is called a superclass.
• A superclass is also referred to as a parent class, or a base
class,
• A subclass is also as a child class, an extended class, or a
derived class.
• A subclass inherits accessible data fields and methods from
its superclass and may also add new data fields and
methods.

Slide 7
Superclass and subclass cont’d
• SYNTAX
public class Derived_Class_Name extends Base_Class_Name
{
Declarations_of_Added_Instance_Variables
Definitions_of_Added__And_Changed_Methods
}

Slide 8
Superclass and subclass cont’d
• Suppose a programmer is to design a college record-
keeping program that has records for students, faculty, and
other staff.
• There is a natural hierarchy for grouping these record
types: They are all records of people. (students, employees,
and so on)
• Hence the superclass can be a Person class with the
student, employee serving as the subclasses

Slide 9
A Class Hierarchy

Slide 10
Implementing a Base class
public class Person{
private String name;
public Person() { name = "No name yet"; }
public Person(String initialName) { name = initialName; }
public void setName(String newName) { name = newName; }
public String getName(){ return name; }
public void writeOutput() { System.out.println("Name: " + name); }
public boolean hasSameName(Person otherPerson) {
return this.name.equalsIgnoreCase(otherPerson.name);
}
}
Slide 11
Extending a Base class
public class Student extends Person {
private int studentNumber;
public Student() {
super();
studentNumber = 0;//Indicating no number yet }
public Student(String initialName, int initialStudentNumber) {
super(initialName);
studentNumber = initialNumber; }
public void reset(String newName, int newStudentNumber) {
setName(newName);
studentNumber = newStudentNumber; }
public int getStudentNumber(){ return studentNumber; }
public void writeOutput() { System.out.println("Student Number: " + studentNumber); }

Slide 12
Using the super Keyword
• The keyword super refers to the superclass of the class in
which super appears.
• It can be used in two ways:
– To call a superclass constructor.
– To call a superclass method.
• The compiler automatically puts super() as the first
statement in the constructor if it is not explicitly invoked.

Slide 13
Calling Superclass Constructors
• The syntax to call a superclass constructor is:
super(), or super(parameters);
• The statement super() invokes the no-arg constructor of its
superclass
• the statement super(arguments) invokes the superclass
constructor that matches the arguments.
• This statement must appear in the first line of the subclass
constructor
• This is the only way to explicitly invoke a superclass
constructor.

Slide 14
Calling Superclass Methods
• The keyword super can also be used to reference a method
other than the constructor in the superclass.
• The syntax is like this:
super.method(parameters);

Slide 15
Overriding Method Definitions
• If a derived class defines a method
– with the same name,
– the same number and types of parameters,
– and the same return type as a method in the base class,
the definition in the derived class is said to override the
definition in the base class.
• The definition in the derived class is the one that is used for
objects of the derived class.
• When overriding a method definition, you cannot change
the return type of the method
• Both methods (in parent class and child class) must have
the same signature and return type.
Slide 16
Overriding Versus Overloading
• When a programmer overrides a method definition, the
new method definition given in the derived class has the
same name, the same return type, and the exact same
number and types of parameters.
• If the method in the derived class has
– the same name and the same return type
– but a different number of parameters or a parameter of a different
type from the method in the base class,
the method names would be overloaded.

• In such cases, the derived class would have both methods.

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 17


The final Modifier
• A method that is not supposed to be overridden by a new
definition within a derived class, must include the final
modifier to the method heading, as in the following sample
heading:
public final void specialMethod()

• An entire class can be declared final, in which case it cannot


be used as a base class to derive any other class.

Slide 18
Topic Two

POLYMORPHISM

Slide 19
Polymorphism
• Polymorphism allows you to make changes in the method
definition for the derived classes and have those changes
apply to the methods written in the base class.
• Polymorphism refers to the ability to associate many
meanings to one method name through the dynamic
binding mechanism.
• With dynamic, or late, binding the definition of a method is
not bound to an invocation of the method until run time
when the method is called.

Slide 20
Dynamic Binding
• A method may be defined in a superclass and overridden in
its subclass.
• Dynamic binding works as follows:
– Suppose an object o is an instance of classes C1, C2,…, Cn-1, and
Cn, where C1 is a subclass of C2, C2 is a subclass of C3,… and Cn-1 is
a subclass of Cn.
– If o invokes a method p, the JVM searches the implementation for
the method p in C1, C2, Cn-1, and Cn, in this order, until it is found.
– Once an implementation is found, the search stops and the first-
found implementation is invoked.

Slide 21
Dynamic Binding cont’d
public class DynamicBindingDemo {
public static void main(String[] args) {
m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Object x) { System.out.println(x.toString()); }
}
class GraduateStudent extends Student { }
class Student extends Person {
public String toString(){ return "Student"; }
}
class Person extends Object {
public String toString(){ return "Person"; }
}

Slide 22
Dynamic Binding cont’d
• The output of the program shows the following:

• The declared type of the reference variable decides which method to


match at compile time.
• The compiler finds a matching method according to parameter type,
number of parameters, and order of the parameters at compile time.
• A method may be implemented in several subclasses. The JVM
dynamically binds the implementation of the method at runtime,
decided by the actual type of the variable.
Slide 23
Topic Three

INTERFACE TYPES

Slide 24
Interfaces
• It is often possible to design a general and reusable
mechanism for processing objects by focusing on the
essential operations that an algorithm needs.
• An interface type is similar to a class, but there are several
important differences:
– All methods in an interface type are abstract; that is, they have a
name, parameter variables, and a return type, but they don’t have
an implementation.
– All methods in an interface type are automatically public.

Slide 25
Interface Syntax
• Declaring:
public interface InterfaceName {
method declarations
}
• Implementing:
public class ClassName implements InterfaceName,
InterfaceName, . . .{
instance variables
methods
}

Slide 26
Why Interfaces?
• Writing an interface is a way for a class designer to specify
methods for another programmer.
• Implementing an interface is a way for a programmer to
guarantee that a class defines certain methods.

Slide 27
Interfaces in action
/**
An interface for methods that return
the perimeter and area of an object.
*/
public interface Measurable
{
/** Returns the perimeter. */
public double getPerimeter();
/** Returns the area. */
public double getArea();
}
Slide 28
Implementing an Interface
// A class of rectangles.
public class Rectangle implements Measurable {
private double myWidth;
private double myHeight;
public Rectangle(double width, double height) {
myWidth = width;
myHeight = height;
}
public double getPerimeter() {
return 2 * (myWidth + myHeight);
}
public double getArea() {
return myWidth * myHeight;
}
}
Slide 29
Implementing an Interface
• Since all data fields are public final static and all methods
are public abstract in an interface, Java allows these
modifiers to be omitted.

• A constant defined in an interface can be accessed using


the syntax InterfaceName.CONSTANT_NAME

Slide 30
Interface as a Type
• An interface is a reference type. Thus, you can write a method
that has a parameter of an interface type.
• For example, suppose that your program defines the following
method:
public static void display(Measurable figure) {
double perimeter = figure.getPerimeter();
double area = figure.getArea();
System.out.println("Perimeter = " +perimeter+ “, area = " + area);
}
• Your program can invoke this method, passing it an object of any
class that implements the interface Measurable.
Slide 31
Extending an Interface
• Another interface can build on, or extends, the first one by
using a kind of inheritance.
• This creates an interface that consists of the methods in an
existing interface plus some new methods.

public interface NewInterface extends Interface1, ...,


InterfaceN {
// constants and abstract methods
}

Slide 32
Abstract Classes
• Sometimes a superclass is so abstract that it cannot have
any specific instances.
• Such a class is referred to as an abstract class.
• An abstract class has at least one abstract method.
• Syntax:
public abstract class ClassName{
//variables and method implementations

public abstract returnType methodName();


}

Slide 33
Interesting Points on Abstract Classes

• An abstract method cannot be contained in a nonabstract


class.
• If a subclass of an abstract superclass does not implement all
the abstract methods, the subclass must be defined abstract.
• An abstract class cannot be instantiated using the new
operator, but you can still define its constructors, which are
invoked in the constructors of its subclasses.
• A class that contains abstract methods must be abstract.
• A subclass can be abstract even if its superclass is concrete.
• A subclass can override a method from its superclass to
define it abstract.
Dr. JAMAL-DEEN ADBULAI, CSCD Slide 34
Interfaces vs. Abstract Classes

Slide 35
References
• Big Java Late Objects (Horstmann, 2012)
• An Introduction to Problem Solving and Programming
(Savitch, 2012)
• Introduction to Java Programming(Liang, 2011)

Slide 36

You might also like