Java Inheritance and Polymorphism

advertisement
Object Oriented Programming
Inheritance and Polymorphism
Kondwani Makanda
kmakanda@must.ac.mw
Outline
●
Introduction
●
Inheritance
●
–
extends keyword
–
Types of Inheritance
–
Advantages
–
Overriding Method
Polymorphism
–
Types of polymorphism
–
Ways of implementing polymorphism
Introduction - Inheritance
●
●
Inheritance is the process where one class acquires
properties of another class
It allows us to create new classes by refining existing
classes
–
●
This allows one to reuse the methods and variables of the
parent class without having to rewrite the code in the new class
The existing class whose properties are inherited is called
parent/superclass/base class and the class that inherits
the properties is called child/subclass/derived class
Inheritance Cont’d
●
Essentially a derived class can inherit data
members of a base class
–
The behaviour of the derived class can be refined
by redefining base class member functions or
adding new member function
–
A key aspect of this is polymorphism where a
classes behaviour can be adapted at run-time
Examples of Inheritance
Base class
Derived class
Shape
Triangle, Circle,
Rectangle
Bank Account
Current, Savings
Student
Undergraduate,
Postgaduate
Vehicle
Car, Truck, Bus
Types of Inheritance
NOTE: Java does not support multiple inheritance
Inheritance: Benefits
●
●
Facilitates code reuse
Allows structuring of classes into logical
hierarchies
is-a relationships, hierarchies
●
is-a relationship: a hierarchical connection where one
category can be treated as a specialized version of
another
–
●
e.g.
●
Every student is a Person
●
Every banker is an employee
Inheritance hierarchy: a set of classes connected by is-a
relationships that can share common code
Inheritance Syntax
class class_name extends superclass_name {
}
Inheritance – extends Keyword
●
To implement inheritance in Java we use the
keyword extends
class Car{
int make_year = 2019;
double max_speed() {
return 300;
}
}
class Toyota extends Car{
String Colour = "Blue";
int number_of_wheels = 4;
}
Types of Inheritance
NOTE: Java does not support multiple inheritance
Overriding
●
●
In Java, variables and methods can be
overridden but methods cannot be overridden if
they are marked final
The advantage of overriding:
–
The ability to define behavior that is specific to the
derived class type – this means that a subclass can
implement a parent class method based on its
requirements
Java Overriding - Example
class Car{
int make_year = 2019;
void max_speed() {
System.out.print("Speed is 300");
}
}
class Toyota extends Car{
String Colour = "Blue";
int number_of_wheels = 4;
void max_speed() {
System.out.println("Speed is 600");
}
}
Some Rules for Method Overriding
●
If a method cannot be inherited, then it cannot be overridden.
●
A method declared final cannot be overridden.
●
Instance methods can be overridden only if they are inherited by the subclass.
●
●
●
●
The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
Constructors cannot be overridden.
The access level cannot be more restrictive than the overridden method's access
level. For example: If the superclass method is declared public then the overriding
method in the sub class cannot be either private or protected.
●
The argument list should be exactly the same as that of the overridden method.
●
A method declared static cannot be overridden but can be re-declared.
super keyword
●
When ever one is trying to invoke a parent
method of an overridden method the super
keyword is used
class Person{
void Stop()
{
System.out.println("The Person has Stopped.");
}
}
class Student extends Person{
void Stop() {
super.Stop();
System.out.println("The Student has Stopped.");
}
}
super keyword
●
When ever one is trying to invoke a parent
method of an overridden method the super
keyword is used
Polymorphism
●
●
●
Polymorphism is the ability for a single a single
action to be performed in so many different
ways.
In polymorphism, we can get many different
types of object behavior from a single reference
type
This allows us to write easily extensible
applications
Polymorphism Cont’d
Polymorphism: Benefits
●
Allows for more flexible code
●
Supports operations on generic objects
●
Drawback:
–
Does make type checking more difficult; requires
more caution at runtime
Types of Polymorphism in Java
●
There are two types of polymorphism in Java
–
Compile time polymorphism (static binding or
method overloading)
–
Runtime polymorphism (dynamic binding or method
overriding)
Polymorphism Cont’d
●
●
Polymorphism allows one to have multiple
methods with the same name in the same class
Polymorphism in Java can be performed by:
–
Method Overloading
●
–
Two or more methods with different signatures
Method Overriding
●
Replacing an inherited method with another having the
same signature
Runtime Polymorphism
●
●
●
●
Runtime polymorphism or Dynamic Method
Dispatch is a process in which a call to an
overridden method is resolved at runtime rather
than compile-time.
In this process, an overridden method is called
through the reference variable of a superclass.
The determination of the method to be called is
based on the object being referred to by the
reference variable.
Example Polymorphism
class Person{
void Stop()
{
System.out.println("The Person has Stopped.");
}
}
class Student extends Person{
void Stop() {
//super.Stop();
System.out.println("The Student has Stopped.");
}
}
public class FirstClass{
public static void main(String[] args) {
Person st = new Student();
st.Stop();
}
}
Example Polymorphism
class Person{
void Stop()
{
System.out.println("The Person has Stopped.");
}
}
class Student extends Person{
void Stop() {
//super.Stop();
System.out.println("The Student has Stopped.");
}
}
public class FirstClass{
public static void main(String[] args) {
Person st = new Student();
st.Stop();
}
}
Runtime Polymorphism Example
Example
class Vehicle
{
public void move()
{
System.out.println("Vehicles can move !!!!");
}
}
class MotorBike extends Vehicle
{
public void move()
{
System.out.println("MotorBike can move and accelerate too!!!");
}
}
class Demo {
public static void main(String[] args)
{
Vehicle obj=new MotorBike();
obj.move();
obj=new Vehicle();
obj.move();
}
}
Compile time/static polymorphism
●
Compile time polymorphism
As the meaning is implicit, this is used to write
the program in such a way, that flow of control
is decided at compile time itself.
●
How to achieve static polymorphism in Java ?
In Java, static polymorphism is achieved
through method overloading.
Method Overloading
●
Method overloading allows a class to have
more than one method having the same name,
if their argument lists are different.
–
This is similar to constructor overloading i.e. a class
having more than one constructor having different
argument lists.
Ways of Overloading Methods
●
There are three ways of overloading a method
a)Number of parameters
e.g.
add(int, int)
add(int, int, int)
b)Data type of parameters
e.g.
add(int, int)
add(int, float)
c)Sequences of Data type of parameters
e.g
add(int, float)
add(float, int)
Example of Compile Time
Polymorphism
Example
public static int add(int a, int b)
{
......
......
}
public static double add(double a, double b)
{
......
......
}
public static float add(float a, float b)
{
......
......
}
Overloading
class Test {
public static void main(String args[]) {
myPrint(5);
myPrint(5.0);
}
static void myPrint(int i) {
System.out.println("int i = " + i);
}
static void myPrint(double d) { // same name, different parameters
System.out.println("double d = " + d);
}
}
int i = 5
double d = 5.0
Why overload a method?
a) So you can use the same names for methods that do essentially the
same thing
–
e.g. println(int), println(double), println(boolean), println(String), etc.
b) So you can supply defaults for the parameters:
int increment(int amount) {
count = count + amount;
return count;
}
int increment() {
return increment(1);
}
–
Notice that one method can call another of the same name
Why overload a method? Cont’d
c) You may want to do “the same thing” with
different kinds of data:
class Student extends Person {
...
void printInformation() {
printPersonalInformation();
printGrades();
}
}
class Professor extends Person() {
...
void printInformation() {
printPersonalInformation();
printResearchInterests();
}
}
Download