0% found this document useful (0 votes)
22 views

Chapter 3 Inheritance and Polymorphism

Uploaded by

sisay alemu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Chapter 3 Inheritance and Polymorphism

Uploaded by

sisay alemu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Chapter 5

(OOP Concepts)

Inheritance and
Polymorphism
10/23/2024 Prepared by: Melkamu D. 1
Encapsulation
• Encapsulation is a practice to bind related functionality
(Methods) & Data (Variables) in a protective wrapper
(Class) with required access modifiers (public, private,
default & protected) so that the code can be saved from
unauthorized access by outer world and can be made easy to
maintain.
• Encapsulation is the technique of making the fields in a
class private and providing access to the fields via public
methods.
• If a field is declared private, it cannot be accessed by anyone outside
the class, thereby hiding the fields within the class.

• For this reason, encapsulation is also referred to as data hiding.


10/23/2024 Prepared by: Melkamu D. 2
Cont…
• The main benefit of encapsulation is the ability to
modify our implemented code without breaking
the code of others who use our code.
• With this feature Encapsulation gives
maintainability, flexibility and extensibility to
our code.

10/23/2024 Prepared by: Melkamu D. 3


Example:
public class EncapTest{
private String name; • The public methods are the
private String idNum; access points to this class'
private int age;
public int getAge(){ fields from the outside java
return age; world.
}
public String getName(){ • Normally, these methods
return name; are referred as getters and
}
public String getIdNum(){ setters.
return idNum;
• Therefore any class that
}
public void setAge( int newAge){ wants to access the
age = newAge; variables should access
}
public void setName(String newName){ them through these getters
name = newName; and setters.
}
public void setIdNum( String newId){
10/23/2024 Prepared by: Melkamu D. 4
idNum = newId;
The variables of the EncapTest class can be access as below:

public class RunEncap{


public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343");
System.out.print("Name : " + encap.getName()+ " Age : "+
encap.getAge());
}} put: : 20
Out s Age
a m e
e: J
Nam
10/23/2024 Prepared by: Melkamu D. 5
get and set methods
• In Java, getter and setter are two conventional methods that
are used for retrieving and updating the value of a variable.
So, a setter is a method that updates the value of a variable.
And a getter is a method that reads the value of a variable.
Getter and setter are also known as accessor and mutator in
Java.
• You learned from the previous chapter that private variables
can only be accessed within the same class (an outside class has
no access to it). However, it is possible to access them if we
provide public get and set methods.
• The get method returns the variable value, and the set method
sets the value.
• Syntax for both is that they start with either get or set, followed
by the name of the variable,
10/23/2024 Preparedwith theD. first letter in upper case:6
by: Melkamu
• Example
• public class Person {
• private String name; // private = restricted access

• // Getter
• public String getName() {
• return name;
• }

• // Setter
• public void setName(String newName) {
• this.name = newName;
• }
• }


• Example explained
• The get method returns the value of the variable name.
• The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.
10/23/2024 Prepared by: Melkamu D. 7
Inheritance
• Inheritance is the process where one object acquires the
properties of another.
• With the use of inheritance the information is made
manageable in a hierarchical order.
• In inheritance the most commonly used keyword would be
extends and implements.
• These words would determine whether one object IS-A
type of another.
• using these keywords we can make one object acquire the
properties of another object.

10/23/2024 Prepared by: Melkamu D. 8


IS-A Relationship:
• IS-A is a way of saying : This object is a type of that
object. Let us see how the extends keyword is used to
achieve inheritance.
public class Animal{
}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal{
}
10/23/2024 Prepared by: Melkamu D. 9
Cont…
• With use of the extends keyword the subclasses will be
able to inherit all the properties of the superclass except
for the private properties of the superclass.

• We can assure that Mammal is actually an Animal with


the use of the instance operator.

10/23/2024 Prepared by: Melkamu D. 10


Example:
public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
l lowi n g re s u lt :
} u l d p ro d u c e the fo
This wo
true
true
true
10/23/2024 Prepared by: Melkamu D. 11
The instanceof Keyword:

• We use the instanceof operator to check or determine


whether Mammal is actually an Animal, and dog is
actually an Animal.

10/23/2024 Prepared by: Melkamu D. 12


HAS-A relationship:

• These relationships are mainly based on the usage.


• This determines whether a certain class HAS-A
certain thing.
• This relationship helps to reduce duplication of code.

10/23/2024 Prepared by: Melkamu D. 13


Example
public class Vehicle{
}
public class Speed{
}
public class Van extends Vehicle{
private Speed sp;
}
This shows that class Van HAS-A Speed. By having a
separate class for Speed, we do not have to put the entire
code that belongs to speed inside the Van class., which
makes it possible to reuse the Speed class in multiple
applications.
10/23/2024 Prepared by: Melkamu D. 14
Cont…
• In Object-Oriented feature, the users do not need to bother
about which object is doing the real work. To achieve this,
the Van class hides the implementation details from the users
of the Van class. So basically what happens is the users
would ask the Van class to do a certain action and the Van
class will either do the work by itself or ask another class to
perform the action.
• A very important fact to remember is that Java only supports
only single inheritance. This means that a class cannot
extend more than one class. Therefore following is illegal:
• public class extends Animal, Mammal{} However, a class
can implement one or more interfaces.
• This has made Java get rid of the impossibility of multiple
10/23/2024 Prepared by: Melkamu D. 15
inheritance
Method Overloading
and
Overriding
10/23/2024 Prepared by: Melkamu D. 16
Overloading

• Overloading is the situation that two or more


methods in the same class have the same name but
different arguments.

• When you have more than one method with the same
name but different arguments, the methods are said to
be overloaded.

10/23/2024 Prepared by: Melkamu D. 17


Example:
public class OverLoadingExample{
public void add(int i, int j){
int k = i + j;
}
public void add(String s, String t){
int k = Integer.parseInt(s) + Integer.parseInt(t);
}
}
 As you can see in the example above, we have the same
method add() taking two parameters but with different
data types.
 Due to overloading we can now call the add method by
either passing it a String
10/23/2024 orby:int.
Prepared Melkamu D. 18
Cont…
• Several restrictions govern an acceptable set of overloaded
methods:
 Any two methods in a set of overloaded functions
must have different argument lists.
 A difference in return type only is not sufficient to
constitute an overload and is illegal.

• Method overloading is generally used where a class can


perform the same operation on more than one type of
data.

10/23/2024 Prepared by: Melkamu D. 19


Overriding
• Overriding means having two methods with the same
arguments, but different implementation. One of them
exists in the Parent class and the another exists in the Child
Class.
• A sub class inherits methods from a super class. Sometimes, the sub
class may want to provide a new version of methods defined in the
super class. This is referred to as method overriding. Method
overriding allows a sub class to provide its own implementation of a
method already provided by one of its super classes.

• The benefit of overriding is: ability to define a behavior that's


specific to the subclass type which means a subclass can implement
a parent class method based on its requirement.

10/23/2024 Prepared by: Melkamu D. 20


Example:
class Animal{
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
Output: n move
a.move();// runs the method in Animal class s ca
Animal walk and run
n
b.move();//Runs the method in Dog class Dogs ca
}
10/23/2024 Prepared by: Melkamu D. 21
Cont…
• In the above example, you can see that the even though b
is a type of Animal it runs the move method in the Dog
class.
• The reason for this is: In compile time, the check is made
on the reference type.
• However, in the runtime, JVM figures out the object type
and would run the method that belongs to that particular
object.
• Therefore, in the above example, the program will
compile properly since Animal class has the method
move.
• Then, at the runtime, it runs the method specific for that
object.
10/23/2024 Prepared by: Melkamu D. 22
Rules for method overriding:
• The return type and argument list must be identical to
those of a method in the super class.
• The accessibility must not be more restrictive than original
method.
• Instance methods can be overridden only if they are
inherited by the subclass.
• If a method cannot be inherited, then it cannot be
overridden.
• 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.
10/23/2024 Prepared by: Melkamu D. 23
Using the super keyword:
• When invoking a superclass version of an overridden method the super
keyword is used.
class Animal{
public void move(){
System.out.println("Animals can move");
} Output: move
a l s ca n
Anim a l k a nd run
} w
Dogs can
class Dog extends Animal{
public void move(){
Super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
Animal b = new Dog(); // Animal reference but Dog object
b.move(); //Runs the methodPrepared
10/23/2024 in Dog classD.
by: Melkamu 24
Polymorphism

10/23/2024 Prepared by: Melkamu D. 25


Polymorphism
• Polymorphism is the ability of an object to take on many
forms.
• It describes a language’s ability to process objects of
various types and classes through a single, uniform
interface.
• Polymorphism in Java has two types:
Compile time polymorphism (static binding) and
Runtime polymorphism (dynamic binding).
• Method overloading is an example of static
polymorphism.
• While method overriding is an example of dynamic
polymorphism.
10/23/2024 Prepared by: Melkamu D. 26
Cont..
• An important example of polymorphism is how a parent
class refers to a child class object.

• In fact, any object that satisfies more than one IS-A


relationship is polymorphic in nature.

• For instance, let’s consider a class Animal and let Cat be


a subclass of Animal. So, any cat IS animal. Here, Cat
satisfies the IS-A relationship for its own type as well as
its super class Animal.

10/23/2024 Prepared by: Melkamu D. 27


Static Polymorphism
• In Java, static polymorphism is achieved through
method overloading.

• Method overloading means there are several methods


present in a class having the same name but
different types/order/number of parameters.

• At compile time, Java knows which method to


invoke by checking the method signatures. So, this is
called compile time polymorphism or static
binding.
10/23/2024 Prepared by: Melkamu D. 28
Example of Static Polymorphism
class DemoOverload{
public int add(int x, int y){ //method 1
return x+y;
}
public int add(int x, int y, int z){ //method 2
return x+y+z;
}
public int add(double x, int y){ //method 3
return (int)x+y;
}
public int add(int x, double y){ //method 4
return x+(int)y;
}
}
class Test{
public static void main(String[] args){
DemoOverload demo=new DemoOverload();
System.out.println(demo.add(2,3)); //method 1 called
System.out.println(demo.add(2,3,4)); //method 2 called
System.out.println(demo.add(2.5,3)); //method 3 called
System.out.println(demo.add(2,3.4)); //method 4 called

}
} 10/23/2024 Prepared by: Melkamu D. 29
Cont…
• In the above example, there are four versions of add
methods. The first method takes two parameters
while the second one takes three.

• For the third and fourth methods there is a change of


order of parameters. The compiler looks at the
method signature and decides which method to
invoke for a particular method call at compile time.

10/23/2024 Prepared by: Melkamu D. 30


Dynamic Polymorphism

• Suppose a sub class overrides a particular


method of the super class.
• Let’s say, in the program we create an object
of the subclass and assign it to the super class
reference.
• Now, if we call the overridden method on the
super class reference then the sub class version
of the method will be called.

10/23/2024 Prepared by: Melkamu D. 31


Example Dynamic Polymorphism
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 Test{
public static void main(String[] args){
Vehicle vh=new MotorBike();
vh.move(); // prints MotorBike can move and accelerate too!!
Vh=new Vehicle();
vh.move(); // prints Vehicles can move!!
}
10/23/2024 Prepared by: Melkamu D. 32
Cont…
• It should be noted that in the first call to move(), the
reference type is Vehicle and the object being
referenced is MotorBike. So, when a call to move() is
made, Java waits until runtime to determine which
object is actually being pointed to by the reference.
In this case, the object is of the class MotorBike. So,
the move() method of MotorBike class will be
called. In the second call to move(), the object is of
the class Vehicle. So, the move() method of Vehicle
will be called.
• As the method to call is determined at runtime, this
is called dynamic binding or late binding.

10/23/2024 Prepared by: Melkamu D. 33


Summary of polymorphic

• An object in Java that passes more than one IS-A tests


is polymorphic in nature
• Every object in Java passes a minimum of two IS-A
tests: one for itself and one for Object class.
• Static polymorphism in Java is achieved by method
overloading
• Dynamic polymorphism in Java is achieved by
method overriding

10/23/2024 Prepared by: Melkamu D. 34


Reading Assignment
 Abstract classes
and Interfaces

10/23/2024 Prepared by: Melkamu D. 35


E ND
T h e
u ! ! !
k Yo
h an
T
10/23/2024 Prepared by: Melkamu D. 36

You might also like