Chapter - 3 Inheritance and Polymorphism

You might also like

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

Course Title: Object Oriented Programming.

Credit Hour: 3 hrs.


ECTS: 5 [2 Lecture , 3 Lab and 2 Tutorial
Hours]
Lecture Schedule: Every _____________
Bedasa Wayessa

OOP- CoSc3112 1
Inheritance and Polymorphism
re-use

Object Oriented Programming - CoSc2051 2


Chapter Outlines
 Introduction Inheritance
 Super-classes and Sub-classes
 Using the super Keyword
 Method Overriding and Overloading
 Polymorphism
 Casting Objects and Instance Operator
 The Object Class
 Abstract Classes
 Interfaces
 Using Interfaces

Object Oriented Programming - CoSc2051 3


Introduction to Inheritance
 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:
 Object inheritance is more well defined!
 Objects that are derived from other object "resemble" their parents
by inheriting both state (fields) and behavior (methods).

Object Oriented Programming - CoSc2051 4


Introduction to Inheritance
 Object-oriented programming allows you to define new classes
from existing classes. This is called inheritance.
 The procedural paradigm focuses on designing methods and the
object-oriented paradigm couples data and methods together into
objects.
 Inheritance is an important and powerful feature for reusing
software.
 what is the best way to design classes so as to avoid redundancy
and make then system easy to comprehend and easy to maintain.
 The answer is to use inheritance.

Object Oriented Programming - CoSc2051 5


Introduction to Inheritance
Superclasses and Subclasses
 Different classes may have some common properties and behaviors:-
 which can be generalized in a class that can be shared by other
classes.
 You can define a specialized class that extends the generalized class.
 The specialized classes inherit the properties and methods from the
general class.
 In Java terminology, a class C1 extended from another class C2 is called
a subclass, and C2 is called a superclass.

Object Oriented Programming - CoSc2051 6


Introduction to Inheritance
Superclasses and Subclasses
 A superclass is also referred to as a parent class or a base class, and a
subclass 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.
 The keyword “extends” used to create inheritance in java.

Object Oriented Programming - CoSc2051 7


Introduction to Inheritance
.

Dog Cat
String name String name
int fleas int hairballs
String getName() String getName()
int getFleas() int getHairballs()
void speak() void speak()

using
inheritance
superclass
Animal
String name subclass
subclass String getName()

Dog Cat
int fleas int hairballs
int getFleas() int getHairballs()
void speak() void speak()

Object Oriented Programming - CoSc2051 8


Introduction to Inheritance
Superclasses and Subclasses
 Note the following points regarding inheritance:
 Contrary to the conventional interpretation, a subclass is not a subset
of its superclass.
 In fact, a subclass usually contains more information and methods
than its superclass.
 Private data fields in a superclass are not accessible outside the class.
 Therefore, they cannot be used directly in a subclass. they can,
however, be accessed/mutated through public accessors/mutators if
defined in the superclass.
 Not all is-a relationships should be modeled using inheritance.

Object Oriented Programming - CoSc2051 9


Recap
1. True or false? A subclass is a subset of a superclass.
2. What keyword do you use to define a subclass?
3. What is single

Object Oriented Programming - CoSc2051 10


Introduction to Inheritance
Using the super Keyword
 The keyword super refers to the superclass and can be used to invoke the
superclass’s methods and constructors.
 A subclass inherits accessible data fields and methods from its superclass.
 The this Reference the calling object.
 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.

 To call superclass method we use super.method(parameters);

Object Oriented Programming - CoSc2051 11


Introduction to Inheritance
Using the super Keyword
 Calling Superclass Constructors:
 A constructor is used to construct an instance of a class.
 Unlike properties and methods, the constructors of a superclass are
not inherited by a subclass.
 They can only be invoked from the constructors of the subclasses
using the keyword super.
 The syntax to call a superclass’s constructor is:
super(), or super(parameters);
public ClassName() {
public ClassName() {
super();
// some statements Equivalent
// some statements
}
}
Object Oriented Programming - CoSc2051 12
Introduction to Inheritance
public class Box {

 Calling
double Superclass Constructors:
width;
double height;

double Adepth;
constructor is used to construct an instance of a class.
 Unlike properties and methods, the constructors of a superclass are
// constructor used when no dimensions specified
not inherited by a subclass.
Box() {
width = -1; // use -1 to indicate
 They =can
height only
-1; // be
aninvoked from the constructors of the subclasses
uninitialized
depth = -1; // box
} using the keyword super.
// constructor
 The syntax used when
to call all dimensions
a superclass’s specified
constructor is:
Box(double w, double h, double d) {
super(),
width = w; heightor = h;super(parameters);
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
} Object Oriented Programming - CoSc2051 13
Introduction to Inheritance
public
// class now
BoxWeight Box uses
{ super to initialize its Box attributes.
public class BoxWeight extends Box{
 Calling
double Superclass Constructors:
width;
double weight;
double height; // weight of box

double Adepth;
constructor is used to construct an instance of a class.
// default
 Unlike constructor
properties and methods, the constructors of a superclass are
// constructor
BoxWeight() { used when no dimensions specified
Box() {not inherited by a subclass.
super();
width == -1;
weight -1; // use -1 to indicate
}  They =can
height -1;only
// be
aninvoked from the constructors of the subclasses
uninitialized
depth = -1; // box
using the keyword super.
} initialize
// width, height, and depth using super()
// constructor
BoxWeight(double
 The syntax used
w, when
double
to call all
h, dimensions
double constructor
a superclass’s specified
d, double m)
is: {
Box(double
super(w,w, h,double
d); //h, double
call d) {
superclass constructor
super(),
width
weight m; heightor
== w; = h;super(parameters);
depth = d;
} }
}// compute and return volume
double volume() {
return width * height * depth;
}
} Object Oriented Programming - CoSc2051 14
Introduction to Inheritance
public
public class
class Box {
TestDemoSuper {
 Calling
double
public Superclass
width;
static Constructors: args) {
void main(String[]
double height;
 Adepth;
double constructor is used to construct an instance of a class.
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
 Unlike
BoxWeight properties
mybox2 = newand methods, the//
BoxWeight(); constructors
default of a superclass are
// constructor used when no dimensions specified
Box()
double{not inherited by a subclass.
vol;
vol=width = -1; // use -1 to indicate
mybox1.volume();
 They =can
height only
-1; // be
aninvoked from the constructors of the subclasses
uninitialized
depth = -1; // box
System.out.println("Volume of mybox1 is " + vol);
using the keyword super.
}System.out.println("Weight of mybox1 is " + mybox1.weight);
// constructor
 The syntax used
System.out.println(); when
to call all dimensions
a superclass’s specified
constructor is:
Box(double w, double h, double d) {
super(),
vol width = w; heightor
= mybox2.volume(); = h;super(parameters);
depth = d;
}System.out.println("Volume of mybox2 is " + vol);
// compute and return volumeof mybox2 is " + mybox2.weight);
System.out.println("Weight
double volume() {
System.out.println();
return
} width * height * depth;
} }
} Object Oriented Programming - CoSc2051 15
Recap
1. What is the output of running the class C in (a)? What problem
arises in compiling the program in (b)?
public class A {

public A() {
System.out.println("A's no-arg constructor is invoked");
}
}
//sub class
class B extends A {}

public class C {
public static void main(String[] args) {
B b = new B();
}
}

Object Oriented Programming - CoSc2051 16


Introduction to Inheritance
Types of Inheritance in Java

Object Oriented Programming - CoSc2051 17


Introduction to Inheritance
Single level Inheritance in Java
 In single inheritance, one class inherits the properties of another.
 It enables a derived class to inherit the properties and behavior
from a single parent class.
 This will, in turn, enable code reusability as well as add new
features to the existing code.

Cat
Extends
Animal
Object Oriented Programming - CoSc2051 18
Introduction to Inheritance
Single level Inheritance in Java
class Animal {
 Invoid
single inheritance, one class inherits the
eat(){System.out.println(“eating”);} properties of
}
another.
class Dog extends Animal {
 Itvoid
enables a derived class to inherit the
bark(){ properties and behavior
System.out.println(“barking”);}
} from a single parent class.

 ThisTestInheritance
class will, in turn, enable
{ code reusability as well as add new
public static void main(String args[]) {
features
Dog d = to theDog();
new existing code.
d.bark();
d.eat();
}
Extends
}

Object Oriented Programming - CoSc2051 19


Introduction to Inheritance
Multi-level Inheritance in Java

 When a class is derived from a class which is also derived from


another class, i.e. a class having more than one parent class but at
different levels, such type of inheritance is called Multilevel
Inheritance.

Extends Extends
Puppy Dog Animal

Object Oriented Programming - CoSc2051 20


Introduction to Inheritance
Multi-level Inheritance in Java
class Animal {
void eat(){System.out.println(“eating…”);}
}
 When a class is derived from a class which is also derived from
class Dog extends Animal {
another class, i.e. a class having more than one
void bark(){System.out.println(“barking…”);} parent class but
}
at different levels, such type of inheritance is called Multilevel
class Puppy extends Dog {
Inheritance.
void weep(){System.out.println(“weeping…”);}
}

class TestInheritance2
Extends { Extends
public
Puppystatic void main(StringDog
args[]) { Animal
Puppy d = new Puppy();
d.weep();
d.bark();
d.eat();
}
}
Object Oriented Programming - CoSc2051 21
Introduction to Inheritance
Recap
 RULE 1: Multiple Inheritance is NOT permitted in Java.
 RULE 2: Cyclic Inheritance is NOT permitted in Java.
 RULE 3: Private members do NOT get inherited.
 RULE 4: Constructors cannot be Inherited in Java.
 RULE 5: In Java, we assign parent reference to child objects.
 RULE 6: Constructors get executed because of super() present
in the constructor.

Object Oriented Programming - CoSc2051 22


Method Overriding and Overloading
Method Overriding
 Re defining the method of the Super Class in the Sub Class.
 Inheritance in java involves a relationship between parent and child
classes.
 Whenever both the classes contain methods with the same name
and arguments or parameters it is certain that one of the methods
will override the other method during execution.
 Method will be called depending on the object.
 Method overriding is achieved in Inheritance.

Object Oriented Programming - CoSc2051 23


Method Overriding and Overloading
Method Overriding
 . class super {
public void display() {
System.out.println(“Hello”);
}
}
class sub extends super {

public void display() {


System.out.println(“Hello Welcome”);
}
}

The same method display in super and sub class

Object Oriented Programming - CoSc2051 24


Method Overriding and Overloading
Method Overriding
 When the sub class object is called then the display method inherited
from the super class is shadowed and the sub class display method is
executed.
 Super Class method never be called upon the object of Sub Class.
 In the given example program the super class have a method called display
which is saying hello and another class sub class is taken where it inherits
the display method from super class and re defines the method.
 When a super class reference holding the object of sub class and
overridden method is called then method of object will be called it is
Dynamic Method Dispatch.

Object Oriented Programming - CoSc2051 25


Method Overriding and Overloading
Method Overriding
 Do’s and Don’ts of Overriding.
 Signature must be same in method overriding.
 If the method name is different the method is not overridden but it is
overloaded.
 Argument may be different but the parameter must be same.
 Return type must be same, if it is not same then the method is neither
overridden nor overloaded.
 Final and static methods cannot be overridden.
 Method can be overridden with same or lenient (public, protected) access
specifiers but the stricter(private) access specifiers cannot be used in sub
class.
Object Oriented Programming - CoSc2051 26
Method Overriding and Overloading
Method Overloading
 Overloading methods enables you to define the methods with the same
name as long as their signatures are different.
 We cannot overload a return type.
 Although we can overload static methods, the arguments or input
parameters have to be different.
 We cannot overload two methods if they only differ by a static keyword.
Like other static methods, the main() method can also be overloaded.
Method(X)
Same class
Method(X, Y)
• You can have this three method in
Method(X, Y, Z)
single class
Object Oriented Programming - CoSc2051 27
Method Overriding and Overloading
Method Overloading
//method overloading
public
. static double max(double num1, double num2) {
if (num1 > num2) {

polymorphism.
It also helps in compile-time
return num1;
} else {
return num2;
}
}
public static int max(int num1, int num2) {
if (num1 > num2) {
return num1;
} else {
return num2;
}
}

Object Oriented Programming - CoSc2051 28


Method Overriding and Overloading
Method Overloading Tips
 Overloading methods can make programs clearer and more readable.
 Methods that perform the same function with different types of
parameters should be given the same name.
 Overloaded methods must have different parameter lists.
 You cannot overload methods based on different modifiers or
return types.
 Sometimes there are two or more possible matches for the invocation
of a method, but the compiler cannot determine the best match. This
is referred to as ambiguous invocation.
 Ambiguous invocation causes a compile error.
Object Oriented Programming - CoSc2051 29
Method Overriding and Overloading
Method Overloading Tips
 Consider the following code:
public class AmbiguousOverloading {

public static void main(String[] args) {

System.out.println(max(1, 2));
ambiguous
}
public static double max(int num1, double num2) {
invocation
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
Object Oriented Programming - CoSc2051 30
Method Overriding and Overloading
Difference between Method Overloading and Method Overriding

Method Overloading Method Overriding

 It is used to increase the readability of the  Provides a specific implementation of the


program method already in the parent class

 It is performed within the same class  It involves multiple classes

 Parameters must be different in case of  Parameters must be same in case of


overloading overriding
 Is an example of compile-time
 It is an example of runtime polymorphism
polymorphism

 Return type can be different but you must


 Return type must be same in overriding
change the parameters as well.

 Overriding does not involve static


 Static methods can be overloaded
methods.
Object Oriented Programming - CoSc2051 31
Polymorphism
 Polymorphism means that a variable of a supertype can refer to a subtype
object.
 Assuming different forms. “Poly” means numerous, and “Morphs”
means forms.
 Polymorphism means that a variable of a supertype can refer to a
subtype object.
 Polymorphism in OOP is the ability of an entity to take several forms.
 Polymorphism literally means “being able to assume different forms.”
 Polymorphism is an important and powerful concept in OOP.
 It is the ability to process objects in a hierarchy differently depending
on their actual class type.
Object Oriented Programming - CoSc2051 32
Polymorphism
 Polymorphism just means that different objects can respond to the
same message in different ways.
 Polymorphism can work for both variables/states and
methods/behaviors of objects.
 However, two powerful polymorphic concepts are often useful when
you define a class: (Types of Polymorphism-)
 method overloading and method overriding.
or Compile-time  and Run-time

 Java implements polymorphism through method overloading and


method overriding.

Object Oriented Programming - CoSc2051 33


Polymorphism
class Shapes {
public void area() {
System.out.println("The formula for area of ");
 Example:
}
}  The human body has different organs. Every organ has a different
class Triangle extends Shapes {
function
public void toarea()
perform;
{
System.out.println("Triangle is ½ * base * height ");
}
}
class Circle extends Shapes {
public void area() {
System.out.println("Circle is 3.14 * radius * radius ");
}
}

Object Oriented Programming - CoSc2051 34


Polymorphism
Dynamic Binding
 A method can be implemented in several classes along the
inheritance chain.
 The JVM decides which method is invoked at runtime.
 A method can be defined in a superclass and overridden in its
subclass.

Object o = new GeometricObject();


System.out.println(o.toString());

Object Oriented Programming - CoSc2051 35


Typecasting in Java
 One object reference can be typecast into another object reference. This is
called casting object.
 In the preceding section, the statement
m(new Student());

 assigns the object new Student() to a parameter of the Object type.


 This statement is equivalent to
Object o = new Student(); // Implicit casting
m(o);

 The statement Object o = new Student(), known as implicit casting, is


legal because an instance of Student is an instance of Object.

Object Oriented Programming - CoSc2051 36


Typecasting in Java
 Student b = (Student)o; // Explicit casting
 It is always possible to cast an instance of a subclass to a variable of a
superclass (known as upcasting).
 Type casting for primitive data type to another.
int age = 45;

// A new value is assigned to newAge


byte newAge = (byte)age;

 However, casting an object reference does not create a new object.


 For example
Object o = new Circle();
Circle c = (Circle)o; // No new object is created

Object Oriented Programming - CoSc2051 37


Abstract Classes
 An abstract class is a class that cannot be instantiated—we
cannot create instances of an abstract class.
 One or more methods may be declared, but not defined. (The
programmer has not yet written code for a few methods).
 The declared methods and classes have the keyword abstract in
their signature.
 There are two types of classes Abstract class and Concrete class.
 If abstract keyword is used before the class then it is an Abstract
Class if nothing is written before class then it is a Concrete class.
 Reference of abstract class is allowed.
Object Oriented Programming - CoSc2051 38
Abstract Classes
Ways to achieve Abstraction in Java

 The process of Abstraction in Java can be achieved by the following two


methods as mentioned below:
 Implementing an Abstract Class
 Implementing an Interface
Abstract class may
 The Syntax for Abstract Classes have also
non-abstract method
//a super abstract class
which has a body
abtract class Super {
abstract void method();
}

 Abstract class can include Abstract and Non-Abstract methods in them.


 They can include constructors and static methods.

Object Oriented Programming - CoSc2051 39


Abstract Classes
//a super abstract class
abstract class Super {
 Object of an Abstract class cannot be created but object of
Super() {
System.out.println(“Super”);
Concrete class can be created.
} abstract class and
void meth1() abstract method
 Reference of abstract
{ class is allowed.
System.out.println(“meth1”);
 Example:
}
abstract void meeth2();
}

//concrete class
class sub extends Super {

Void meth2() {
System.out.println(“meth2”);
}
}
Object Oriented Programming - CoSc2051 40
Abstract Classes
class test {

public static void main() {

Super s1; // reference of abstract is allowed

sub s2 =new sub();

}
}

 Object of an Abstract class cannot be created but object of Concrete class can be created.
 Reference of abstract class is allowed.
 Example:
 Method which is not having a body is known as Abstract method, the method must be declared as
abstract.
 The abstract method is undefined method.
 A class is Abstract class if at least one of the methods is abstract.
Object Oriented Programming - CoSc2051 41
Abstract Classes
 If any other class inherits abstract class then that class also
becomes abstract class but to become a concrete class the subclass
must override the undefined method.
 A class becomes useful if it overrides all the methods of abstract
class
 Abstract classes are used for imposing standards and sharing
methods
 Sub classes are meant for following standards.

Object Oriented Programming - CoSc2051 42


Abstract Classes
Do’s and Don’ts of Abstract Class
 An Abstract class cannot be final because if it is made final then it
cannot be extended whereas abstract class is meant for
inheritance.
 An Abstract method cannot be final because if it made final then
it cannot be overridden whereas Abstract method is meant for
overriding.
 Abstract Class and method can neither be final nor static.
 A Sub class must override an abstract method or else it will
become abstract class.
Object Oriented Programming - CoSc2051 43
Interfaces
 Inheritance is used for borrowing methods.
 Abstract is used for achieving polymorphism as well as
Inheritance.
 Inheritance is completely used for achieving Polymorphism.
 Interface can be call as Abstract Class with all abstract methods.
 All the methods are by default abstract.
 Classes are extended but Interfaces are implemented.
 In Interface we can have reference of interface and the object of the
class which is implemented.

Object Oriented Programming - CoSc2051 44


Interfaces
 In java a class can extend from one class only but if a class is
implementing an interface then it can implement from multiple
interfaces.
 An interface in Java is a collection of abstract methods and static
constants.
 As you might know in an interface, each method is public and abstract
but it does not contain any constructor.
 Along with abstraction, the interface also helps to achieve multiple
inheritance in Java.
 Note: You can achieve 100% abstraction using interfaces.

Object Oriented Programming - CoSc2051 45


Interfaces
Example Program
Interface

interface test1 {
void meth1(); Collection of abstract method
void meth2();
}
class test2 implements test1 {
public void meth1() {}
Implementation of abstract
public void meth2() {} method in derived class
}
class test {
public static void main(String[] args){
test1 t=new test2 (); Creating an object derived class
t. meth1();
} Calling method
}
Object Oriented Programming - CoSc2051 46
Interfaces
Do’s and Don’ts of Interfaces
 By default, methods are Public and Abstract.
 As methods are to be implemented by the classes, they can’t be
made private.
 Identifiers can be used in interfaces but the identifiers must be
given in Upper cases.
 Identifiers are by default final and static.
 Method inside an interface cannot have body but the method can
have body if the method is static.
 Static members can be accessed in main method by using interface
name and dot operator. Object Oriented Programming - CoSc2051 47
Interfaces
Do’s and Don’ts of Interfaces
 An interface can be extended from another interface.
Interface VS Multiple
Inheritance
 In C++ one class can inherit from multiple classes.
 Multiple Inheritance in java is achieved using Interfaces.
 Interfaces are perfect than using Multiple Inheritance.
 Way of thinking in java is more perfect than C++.

Object Oriented Programming - CoSc2051 48


Difference between Interface and Abstract Class
Interface Abstract Class
 Can have Abstract and Non-Abstract
 Can have only Abstract Methods
. Methods
 It has only Final Variables  It includes Non-Final Variables
 It has Static, Non-Static, final, Non-
 It has Static and Final variables only
Final variables
 Will not implement the Abstract
 Can implement an Interface
Class
 Implemented using “implements”  Implemented using “extends”
Keyword Keyword
 Can extend Java Classes and
 Can extend only an Interface
Interfaces
 Members can be Private and
 Members are Public by default
Protected

Object Oriented Programming - CoSc2051 49


Abstraction vs Encapsulation
Abstraction Encapsulation
. Solves the problem in design  Solves the problem in the
level implementation level

 Encapsulation means hiding


 Used for hiding unwanted
the code and data into a
data and giving relevant
single unit to protect data
results.
from the outside world

 Outer layout – used in terms of  Inner layout – used in terms


design of implementation

Object Oriented Programming - CoSc2051 50


Bye

Take a look : https://docs.oracle.com/en/java/

Object Oriented Programming - CoSc2051 51

You might also like