Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 72

CSE 2202 Object Oriented Programming ASTU

(OOP)

Inheritance and Polymorphism

2019

Computer Science & Engineering Program


The School of EE & Computing
Adama Science & Technology University
Outline ASTU

Inheritance
– What is Inheritance
– Advantage of inheritance
– Types of Inheritance
Aggregation
Supper and Final Keyword
Polymorphism
Overloading and Overriding Methods
 Abstract Class

2
What is Inheritance? ASTU

 In the real world: We inherit traits from our


mother and father. We also inherit traits from
our grandmother, grandfather, and ancestors.
We might have similar eyes, the same smile, a
different height . . . but we are in many ways
"derived" from our parents.

 In software: Inheritance in java is a mechanism in


which one object acquires all the properties and be-
haviors of parent object

3
Example of Inheritance ASTU

Student GraduateStudent, UndergraduateStudent

Shape Circle, Triangle, Rectangle

Loan CarLoan, HomeImprovementLoan, MortgageLoan

Employee Admin staff, academic Staff

BankAccount CheckingAccount, SavingsAccount

4
Contd. ASTU

5
Contd. ASTU

 Inheritance enables the programmer to write a class


based on an already existing class.
 The already existing class is called the parent class,
or superclass, and the new class is called the sub-
class, or derived class.
 The subclass inherits (reuses) the non-private mem-
bers (methods and variables) of the superclass, and
may define its own members as well.
 Inheritance is implemented in Java using the key-
word extends.
 When class B is a subclass of class A, we say B extends A.
6
Syntax of Inheritance ASTU

Class Subclass-name extends Superclass-name


{
//methods and fields
}
Example:
class car extends vehicle
{
//class contents
}

7
Contd. ASTU

 Inheritance represents the IS-A relationship, also


known as parent-child relationship.
 Inheritance relationships often are shown graphically
in a UML class diagram, with an arrow with an open
arrowhead pointing to the parent class.

 Inheritance should create an is-a relationship,


meaning the child is a more specific version of the
parent.
8
Advantages of Inheritance. ASTU

 Code reusability:-Inheritance automates the


process of reusing the code of the superclasses in
the subclasses.
 With inheritance, an object can inherit its more general
properties from its parent object, and that saves the
redundancy in programming.
 Code maintenance:- Organizing code into hierarchi-
cal classes makes its maintenance and management
easier.
 Implementing OOP:- Inheritance helps to imple-
ment the basic OOP philosophy to adapt computing
to the problem and not the other way around, be-
cause entities (objects) in the real world are often
organized into a hierarchy.
9
Contd. ASTU

If we develop any application using concept of Inheri-


tance than that application have following advantages,

 Application development time is less.


 Application take less memory.
 Application execution time is less.
 Application performance is enhance (improved).
 Redundancy (repetition) of the code is reduced or min-
imized so that we get consistence results and less
storage cost.

10
Problem: Code Duplication ASTU

• Classes often have a lot of state and


behavior in common

• Result: lots of duplicate code!

11
Solution: Inheritance ASTU

• Inheritance allows you to write new classes


that inherit from existing classes

• The existing class whose properties are


inherited is called the "parent" or superclass

• The new class that inherits from the super


class is called the "child" or subclass

• Result: Lots of code reuse!

12
weeklyEmp PartTimeEMP
String name String name ASTU
int id,nwk; int id,wkhr;
folat weeklyrate; float sal,Rate;
Float salary; String getName()
String getName() int getid()
int getid() using
inheritance

Employee
String name
superclass Int id;
Float salary;
String getName() subclass
int getid()
subclass

weeklyEmp partTimeEmp
float weeklyrate; int wkhr;
int nwk; float rate;
13
ASTU
Employee Superclass

public class Employee{

private String name;


float salary;
int id;

public Employee(String n,int id) {


name = n;
this.id=id;
}
public String getName(){ return name; }

public int getid() { return id; }

}
14
ASTU
partimeEmp Subclass

public class partimeEmp extends Employee{

private int rate,whr;

public partimeEmp (String n, int i,int r,int


h) {
super(n,i);//calls Employee constructor
rate = r;
Whr=h;
}

public void setsal() {


salary=rate*whr;
}

}
15
ASTU
WeeklyEmp Subclass

public class WeeklyEmp extends Employee{

private int wrate,nwk;

public weeklyEmp(String n, int i,int r,int nw)


{
super(n,i);//calls Employee constructor
wrate = r;
nwk=nw;

public void setSal() {


salary=wrate*nw;
}

} 16
ASTU
Inheritance Quiz-1

• What is the output of the following?

Class test{
Public static void main(String args[])
{
weeklyEmp WEmp1=new weeklyemp(“abebe”,12,120,5);
wEmp1.setSal();
partimeEmp PEmp= new partimeEmp(“Bekele”,13,30,120);
PEmp.setsal();
}
}

17
ASTU
Inheritance Rules

• Use the extends keyword to indicate that


one class inherits from another

• The subclass inherits all the nonprivate fields


and methods of the superclass

• Use the super keyword in the subclass


constructor to call the superclass constructor

18
Subclass Constructor ASTU

• The first thing a subclass constructor must do


is call the superclass constructor using super
keyword

• This ensures that the superclass part of the


object is constructed before the subclass part

• If you do not call the superclass constructor


with the super keyword, and the superclass
has a constructor with no arguments, then that
superclass constructor will be called implicitly.

19
Inheritance Types ASTU

A. Single level inheritance:- Inheritance in which a


class inherits from only one super class.
B. Multi-level inheritance:- Inheritance in which a
class inherits from a class which itself inherits from
another class.
 Here a minimum of three classes is required.
C. Hierarchy inheritance:- Here two or more classes
inherits from one class.
D. Multiple inheritance:- A class inherits from two or
more classes.
 This type of inheritance is not supported in Java.
E. Hybrid inheritance :- is supported through interface
only.

20
Inheritance Types ASTU

21
ASTU
Single Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Out put:
barking…
eating...
22
ASTU
Multilevel Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Out put:
weeping…
barking…
eating…
23
ASTU
Hierarchical Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
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();
//c.bark();//C.T.Error
}}

Out put:
meowing…
eating…
24
ASTU
Why multiple inheritance is not supported in java?
 To reduce the complexity and simplify the language, multiple
inheritance is not supported in java.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

Public Static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}

25
Inheritance Quiz-2 ASTU

public class A {
public A() { System.out.println("I'm A"); }
}

public class B extends A {


public B() { System.out.println("I'm B"); }
}

public class C extends B {


public C() { System.out.println("I'm C"); }
}

What does this print out? I'm A


I'm B
C x = new C(); I'm C
26
Polymorphism ASTU

• Is a concept by which we can perform a single action


in different ways.
• Polymorphism is derived from 2 greek words: poly and
morphs. The word "poly" means many and "morphs"
means forms. So polymorphism means many forms.
• There are two types of polymorphism in java: compile
time polymorphism and runtime polymorphism.

• We can perform polymorphism in java by method


overloading and method overriding.

• If you overload static method in java, it is the example


of compile time polymorphism

27
Example of polymorphism ASTU

Student
Person
Employee

Rectangle

Shape Triangle

Circle

28
Runtime Polymorphism ASTU

• 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.

• 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.

29
Up casting ASTU

• When reference variable of Parent class


refers to the object of Child class, it is
known as up casting

class A{}
class B extends A{}
A a=new B();//upcasting
30
Example of Runtime Polymorphism ASTU

class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");
}
public static void main(String args[]){
Bike b = new Splender();//upcasting
b.run();
}
}
Output: running safely with 60km

31
Runtime Polymorphism with data member ASTU

• Method is overridden not the data members, so runtime


polymorphism can’t be achieved by data members.
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;

public static void main(String args[]){


Bike obj=new Honda3();
System.out.println(obj.speedlimit);
}
Output: 90
32
Runtime Polymorphism with Multilevel Inheritance ASTU

class Animal{
void eat(){System.out.println("eating");}
}
class Dog extends Animal{
void eat(){System.out.println("eating meat");}
}
class BabyDog extends Dog{
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
} }
Output: eating
eating meat
drinking milk
33
An example that illustrates dynamic method dispatch ASTU

// Dynamic Method Dispatch class Dispatch {


class A { public static void main(String args[]) {
void callme() { A a = new A(); // object of type A
System.out.println("Inside A's callme method"); B b = new B(); // object of type B
} C c = new C(); // object of type C
} A r; // obtain a reference of type A
class B extends A { r = a; // r refers to an A’s object
// override callme() r.callme(); // calls A's version of callme
void callme() { r = b; // r refers to a B’s object
System.out.println("Inside B's callme method"); r.callme(); // calls B's version of callme
} r = c; // r refers to a C ‘s object
} r.callme(); // calls C's version of callme
class C extends A { }
// override callme() }
void callme() {
System.out.println("Inside C's callme method");
}
} OUTPUT:
Inside A's callme method
Inside B's callme method
Inside C's callme method

34
An example that illustrates dynamic method dispatch: ASTU

 Discussion:
• Also, a reference of type A, called r, is declared. The program then
assigns a reference to each type of object to r and uses that reference to
invoke callme().
• The version of callme() executed is determined by the type of object
being referred to at the time of the call. Had it been determined by the
type of the reference variable, r, you would see three calls to A’s
callme() method.

35
Quiz ASTU

What is the output?


class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
}
class BabyDog1 extends Dog{
public static void main(String args[]){
Animal a=new BabyDog1();
a.eat();
}}

36
Method overloading ASTU

• Whenever same method name with different


arguments in the same class with
 different number of parameter or
different order of parameters or
different types of parameters is
known as method overloading.

37
Different ways to overload the method ASTU

• There are two ways to overload the method in


java
 By changing number of arguments
or parameters
 By changing the data type

38
By changing number of argument ASTU

class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10, 20, 30);
}
}
39
By changing data type ASTU

class Addition
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(float a, float b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10.05, 15.20);
}
}
40
Method Overriding ASTU

• Whenever same method name is existing in


both base class and derived class with same
types of parameters or same order of
parameters is known as method Overriding.
• Advantage of Java Method Overriding
 Method Overriding is used to provide
specific implementation of a method that is
already provided by its super class.
 Method Overriding is used for Runtime
Polymorphism
41
Rules for Method Overriding ASTU

 Method must have same name as in the


parent class.
 Method must have same parameter as in
the parent class.
 Must be IS-A relationship (inheritance).

42
Example ASTU

class Walking class OverridingDemo


{ {
void walk() public static void main(String
{ args[])
System.out.println("Man {
walking fastly"); Man obj = new Man();
} obj.walk();
} }
class Man extends walking }
{
void walk()
{
System.out.println("Man
walking slowly");
}
}

43
without method overriding ASTU

class Vehicle{
void run(){System.out.println("Vehicle is running");}

}
class Bike extends Vehicle{
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}
}
Output: Vehicle is running

44
Example ASTU

class Vehicle{
void run(){
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle{
void run(){
System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}
Output: Bike is running safely

45
method overriding ASTU

• Whenever we are calling overridden method


using derived class object reference the
highest priority is given to current class
(derived class).

46
Real example of Java Method Overriding ASTU

• Consider a scenario, Bank is a class that provides functionality to


get rate of interest. But, rate of interest varies according to
banks. For example, Nibe, Oromia and Dashen banks could
provide 8%, 7% and 9% rate of interest.

47
Real example of Java Method Overriding ASTU

class Bank{
int getRateOfInterest(){return 0;}
}
class Nibe extends Bank{
int getRateOfInterest(){return 8;}
}
class Oromia extends Bank{
int getRateOfInterest(){return 7;}
}
class Dashen extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
Nibe s=new Nibe();
Oromia i=new Oromia();
Dashen a=new Dashen();
System.out.println(" Nibe Rate of Interest: "+s.getRateOfInterest());
System.out.println(" Oromia Rate of Interest: "+i.getRateOfInterest());
System.out.println(" Dashen Rate of Interest: "+a.getRateOfInterest());
}
48
ASTU
Java useful keywords

 Super keyword
 Final keyword
 Static keyword
 This keyword

49
ASTU
Super key word
• The super keyword in java is a reference
variable that is used to refer immediate
parent class object.

• Whenever you create the instance of


subclass, an instance of parent class is
created implicitly i.e. referred by super
reference variable.

50
ASTU
use of Super key word

1. super is used to refer immediate parent


class instance variable.
2. super() is used to invoke immediate
parent class constructor.
3. super is used to invoke immediate parent
class method.

51
used to refer immediate parent class instance variable. ASTU

class Vehicle{
int speed=50;
}
class Bike3 extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]){
Bike3 b=new Bike3();
b.display();
}
}

Output: 100
52
used to refer immediate parent class instance variable. ASTU

class Vehicle{
int speed=50;
}
class Bike3 extends Vehicle{
int speed=100;
void display(){
System.out.println(Super.speed);//will print speed of Vehicle
}
public static void main(String args[]){
Bike3 b=new Bike3();
b.display();
}
}

Output: 50
53
ASTU
used to invoke parent class constructor
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike5 extends Vehicle{
Bike5(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();
}
}
Output:
Vehicle is created
Bike is created
54
ASTU
used to invoke parent class method
class Person{
void message(){System.out.println("welcome");}
}
class Student16 extends Person{
void message(){System.out.println("welcome to java");}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student16 s=new Student16();
s.display();
}
}
Output:
welcome to java
welcome 55
Final keyword ASTU

• It is used to make a variable as a


constant, Restrict method overriding,
Restrict inheritance.

A class in java contains:


 Final at variable level
 Final at method level
 Final at class level

56
Final at variable level ASTU

• A variable declared with the final keyword


cannot be modified by the program after
initialization. This is useful to universal
constants, such as "PI".
public class Circle
{
public static final double PI=3.14159;
public static void main(String[] args)
{System.out.println(PI);
}
}
57
Final at method level ASTU

• It makes a method final, meaning that sub classes can not


override this method. The compiler checks and gives an error
if you try to override the method.

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
Output: Compile time error 58
Final at class level ASTU

• It makes a class final, meaning that the class can not be


inherited by other classes. When we want to restrict
inheritance then make class as a final.

final class Bike{}

class Honda1 extends Bike{


void run()
{System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda();
honda.run();
}
} 59
Rule to use this() ASTU

• this() always should be the first


statement of the constructor. One
constructor can call only other single
constructor at a time by using this().

60
Example without using this keyword ASTU

class Employee
{ int id;
String name;
Employee(int id,String name)
{
id = id; name = name;
}
void show()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Employee e1 = new Employee(111,"Harry");
Employee e2 = new Employee(112,"Jacy");
e1.show();
e2.show();
}
}
Output:
0
0
null
null
61
Example with this keyword ASTU

class Employee
{ int id;
String name;
Employee(int id,String name)
{
this. id = id; this.name = name;
}
void show()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Employee e1 = new Employee(111,“Abel");
Employee e2 = new Employee(112,“Surafel ");
e1.show();
e2.show();
}
}
Output:

62
111 Abel
112 Surafel
Aggregation in Java- HAS-A relationship. ASTU

• If a class have an entity reference, it is known as Aggregation.


When we use Aggregation :
Code reuse is also best achieved by aggregation when there is no is-a
relationship.

Consider a situation, Employee object contains many informations


such as id, name, emailId etc. It contains one more object named
address, which contains its own informations such as city, state,
country, zipcode etc. as given below.

class Employee{
int id;
String name;
Address address;//Address is a class
...
}
63
Example of aggregation ASTU

public class Address {


Emp.java
public class Emp {

String city,state,country;
int id;
String name;
Address address;

public Emp(int id, String name,Address address) {


this.id = id;

public Address(String ci this.name = name;


this.address=address;
ty, String state, String co }

untry) { void display(){


System.out.println(id+" "+name);
this.city = city; System.out.println(address.city+" "+address.state+" "+address.countr
y);
this.state = state; }

this.country = count public static void main(String[] args) {


Address address1=new Address("gzb","UP","india");
ry; Address address2=new Address("gno","UP","india");

} Emp e=new Emp(111,"varun",address1);


Emp e2=new Emp(112,"arun",address2);

e.display();
} e2.display(); } }

64
Abstract class in java ASTU

• We know that every java program must


start with a concept of class that is
without classes there is no java
program
• In java programming we have two types
of class
Concrete class in Java
• A concrete class is one which is
containing fully defined methods or
implemented method.
65
Example for concrete class ASTU

class Helloworld
{
void display()
{
System.out.println("Good Morning........");
}
}
Create an object
Helloworld obj=new Helloworld();
obj.display();
66
Abstract class ASTU

• An abstract class is one which contains


some defined methods and some
undefined
• Undefined methods are also known as
unimplemented or abstract methods
• To make the method as abstract we have
to use a keyword called abstract before
the function declaration

67
Contd. ASTU

 While using abstract classes:

 We cannot use abstract classes to instantiate objects directly.

 The abstract method of an abstract class must be defined in


its subclass.
 We cannot declare abstract constructors or abstract static
methods.
 Abstract classes can have none, one or more abstract meth-
ods and one or more non abstract methods
 A subclass of abstract class should be implements all abstract
methods

68
Contd. ASTU

Syntax for ABSTRACT CLASS:


abstract class <clsname>
{
Abstract return_type method_name (method
parameters if any);
};
• With respect to abstract class we cannot create
an object direct but we can create indirectly.

69
Contd. ASTU

• An object abstract class is equal to an object


of class which extends abstract class.
For Example:
class CC extends AC
{………;
………;
};
AC Ao=new AC (); //invalid
AC Ao=new CC ();
or
AC Ao;
Ao=new CC ();

70
Example ASTU

abstract class Shape{


abstract void draw();
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}

class Circle1 extends Shape{


void draw(){System.out.println("drawing circle");}
}

//In real scenario, method is called by programmer or user


class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1(); 71
ASTU

Thank You
?

72

You might also like