0% found this document useful (0 votes)
33 views96 pages

Unit 25t

The document provides an overview of Object Oriented Programming (OOP) in Java, detailing its fundamental principles such as Abstraction, Encapsulation, Inheritance, and Polymorphism. It explains key concepts including classes, objects, access modifiers, constructors, and the use of the super keyword in inheritance. Additionally, it highlights the advantages of OOP features like code reusability and flexibility in programming.

Uploaded by

punitmeme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views96 pages

Unit 25t

The document provides an overview of Object Oriented Programming (OOP) in Java, detailing its fundamental principles such as Abstraction, Encapsulation, Inheritance, and Polymorphism. It explains key concepts including classes, objects, access modifiers, constructors, and the use of the super keyword in inheritance. Additionally, it highlights the advantages of OOP features like code reusability and flexibility in programming.

Uploaded by

punitmeme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 96

Unit 2

Object Oriented
Programming in Java

Prepared By: Er. Sudarshan Subedi


Object Oriented Programming(OOP)
Object-oriented programming (OOP) is a computer programming
model that organizes software design around data, or objects, rather
than functions and logic.
It is a programming pattern that rounds around an object or entity.
The major principles/pillars of OOP are:
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Note: We will study bout these concepts in detail in further slides

Prepared By: Er. Sudarshan Subedi


Object Oriented Programming Features-Abstraction
Abstraction is hiding the internal details and showing only essential
functionality.
In the abstraction concept, we do not show the actual implementation
to the end user, instead we provide only essential things.
For example, if we want to drive a car, we do not need to know about
the internal functionality like how wheel system works? how brake
system works? how music system works? etc.
There are generally two types of abstraction.
a. Data Abstraction: When the object data is not visible to the outer world, it
creates data abstraction.
b. Function/Process Abstraction: When we hide the internal implementation
and do not disclose all the details about a method or function to the users, this
is known as Process abstraction.
Prepared By: Er. Sudarshan Subedi
Object Oriented Programming Features-Encapsulation
Encapsulation is the process of combining data and
function into a single unit (object / class).
In OOP, every object is associated with its data and
code/function.
In programming, data is defined as variables and code
is defined as methods.
 Encapsulation can be achieved using access specifiers.
In encapsulation we make member variables private. If
a data member is private, it means it can only be
accessed within the same class. No outside class can
access private data member or variable of other class.
These variables are bundled with methods that provide
read and write access to them. Prepared By: Er. Sudarshan Subedi
Object Oriented Programming Features-Inheritance
Feature of OOP that enables new classes to receive or inherit the
properties and methods of existing classes i.e. from base class to
derived class.
Inheritance provides code reusability. The same base classes can be
used by a number of derived class. Hence it saves time and effort as
the main code need not be written again.

Prepared By: Er. Sudarshan Subedi


Object Oriented Programming Features-Inheritance

Advantages of Inheritance:
1. Reusability: It is a reuse mechanism at
both the design and the programming
level. Code Reusability is one of the major
advantage of Inheritance.
2. It is an abstraction mechanism which may
be used to classify entities
3. The inheritance graph is a source of
organisational knowledge about domains
and systems

Prepared By: Er. Sudarshan Subedi


Object Oriented Programming Features-Polymorphism
The word polymorphism came from two Greek words ‘poly‘ and
‘morphs‘. Here poly means many and morphs means forms.
The word polymorphism means having many forms.
In OOP, polymorphism refers to the ability of object to take different
forms.
 Polymorphism provides flexibility to the programmer to write
programs that uses single method for different operations depending
on the requirement.

Prepared By: Er. Sudarshan Subedi


Object Oriented Programming Features-Polymorphism
Basically there are two types of polymorphism:
a. Compile-Time polymorphism: It is the type of polymorphism that
is implemented when the compiler compiles a program.
Function overloading(Having same function name but different
number of arguments) is an example of Compile- time
polymorphism. It is also called as static binding.
b. Run-Time polymorphism: The type of polymorphism that is
implemented dynamically when a program being executed is
called run-time polymorphism. Function overriding(When child
class declares a method, which is already present in the parent
class) is an example of Run-time polymorphism. It is also called as
dynamic binding.
Prepared By: Er. Sudarshan Subedi
Object Oriented Programming
Object-oriented programming (OOP) is a programming paradigm
based on the concept of objects and classes to organize the data
Objects
Objects are the real world entities having:
• State: It is represented by attributes of an object. It also reflects the
properties of an object.
• Behavior: It is represented by methods of an object. It also reflects
the response of an object with other objects.
• Identity: It gives a unique name to an object and enables one object
to interact with other objects.
For example: bike is an object. It has:
State: gear, speed
Behavior: braking, accelerating, changing gears, etc.
Prepared By: Er. Sudarshan Subedi
Object Oriented Programming

Class
A class can also be defined as a blueprint from which you can create
an individual object. Class doesn't consume any space.
Collection of objects is called class. It is a logical entity.
A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common
to all objects of one type.
We can think of the class as a sketch(prototype) of a house. It contains
all the details about the floors, doors, windows, etc. Based on these
description, we build the house. The house is an object.

Prepared By: Er. Sudarshan Subedi


Object Oriented Programming-Class and Object

Prepared By: Er. Sudarshan Subedi


Java Class and Objects

We can create a class in Java using following syntax:


class className{
fields or variables or dataMembers or attributes
methods
}
 Here fields (variables) and methods represent the state and behavior
of the object respectively
• Fields are used to store data
• Methods are used to perform some operations on fields

Prepared By: Er. Sudarshan Subedi


Java Class and Objects

As an example, we can create Bike class as:

class Bike{
int speed =50; //fields or variables
public void brake(){ //method
System.out.println(“Applying Brakes”);
}
}

Prepared By: Er. Sudarshan Subedi


Java Class and Objects
We can create the object of a class as:
ClassName objectName = new ClassName();
Suppose we have created the blueprint for bikes i.e. the Bike class.
Now we can use it to create any number of bikes.
All bikes made using this blueprint will share the fields and
methods of the blueprint.
An object is instance of a class.
We can create objects of class Bike as follows:
Bike dirtBike = new Bike();

Prepared By: Er. Sudarshan Subedi


Java Class and Objects
Here, dirtBike is an object of class Bike and it will have all the fields
and methods described in the class.
We can create multiple objects from same class as well.
Bike dirtBike = new Bike();
Bike sportsBike = new Bike();
Bike cruiserBike = new Bike();

Prepared By: Er. Sudarshan Subedi


Java Class and Objects-Accessing Members of a Class

We can use the name of objects


along with the . operator (dot
operator) to access the members
of a class.

Prepared By: Er. Sudarshan Subedi


Java Class and Objects-Accessing Members of a Class

Prepared By: Er. Sudarshan Subedi


Java Access Modifier-Example
In example aside, burnPetrol()
method is made private that means it
cannot be accessed by other classes.
From MainClass class, we cannot
directly call burnPetrol() via object
of Bike class.
However, brake() and accelerate()
are public meaning they can be
accessed by other classes.

Prepared By: Er. Sudarshan Subedi


Java Access Modifier-Java Default Access Modifier

If we do not explicitly specify any access modifier for classes,


methods, variables, etc., then by default the default access modifier
is considered.

Here Logger class has default access modifier.


The class is visible to all the classes that belong to defaultPackage
package.
However if we try to use the Logger class in any class outside of the
defaultPackage, we will get a compilation error.

Prepared By: Er. Sudarshan Subedi


Java Access Modifier-Private Access Modifier

When variables and methods are declared private, they cannot be


accessed outside of the class.
Classes cannot be private
When we run the program aside, we will get an error.
Note: In order to access private methods and fields, we need getters
and setters methods

Prepared By: Er. Sudarshan Subedi


Getters and Setters

Getter and setter methods can be used to get and set the values of an
object respectively.
The setter method takes one or more arguments and then sets the
values of those arguments to the variables/fields of object.
i.e. setters are used to initialize objects
Syntax:
public void setterName(dataType arg1, datatype arg2){
//code to set the value of received argument to the variables/fields of
objects
}
Prepared By: Er. Sudarshan Subedi
Getters and Setters

Getter methods are used to retrieve the values set on object.


Syntax:
public returnType getterName(){
return field;
}
The returnType of the method should be the type of the field whose
value is to be returned.

Prepared By: Er. Sudarshan Subedi


Java Access Modifier-Private Access Modifier
If we need to access those private variables, we can use the getters
and setters method.

Prepared By: Er. Sudarshan Subedi


Java Access Modifier-Private Access Modifier
Getter Setter Example
Write program to create a class named Employee. The class must have
private fields like employeeId, name, position. Create an object of the
Employee class from another class(i.e. the class that has the main
method), initialize the object and display the initialized values using
getters and setter.

Prepared By: Er. Sudarshan Subedi


Java Access Modifier-Protected Access Modifier
When variables and methods are declared protected, they can be
accessed within the same package as well as from its subclasses.
Note: We cannot declare class as protected in Java

Output

Prepared By: Er. Sudarshan Subedi


Java Access Modifier-Public Access Modifier
When variables, classes, methods are declared public, they can be
accessed from anywhere.

Prepared By: Er. Sudarshan Subedi


Constructors In Java
A constructor in Java is a special method that is used to initialize objects
but doesn’t have a return type.
Constructor’s name must match the class name i.e. constructor name
should be the name of class
The constructor is called when an object of a class is created. It can be used
to set initial values for object attributes.
Syntax:
class className{
className(){
}
}
There are two types of constructors in Java:
a. Default constructor (no-argPrepared
constructor)
By: Er. Sudarshan Subedi
b. Parameterized constructor
Constructors in Java-How Constructors are Different From
Methods in Java?

Constructors must have the same name as the class within which it is
defined while it is not necessary for the method in Java.
Constructors do not return any type while method(s) have the return
type or void if does not return any value.
Constructors are called only once at the time of Object creation while
method(s) can be called any number of times.

Prepared By: Er. Sudarshan Subedi


Constructors In Java-Default Constructor
A constructor is called "Default Constructor" when it doesn't have any
parameter.
The default constructor is used to provide the default values to the
object like 0, null, etc., depending on the type.
Default constructor is called on creating object

Prepared By: Er. Sudarshan Subedi


Constructors In Java-Default Constructor

Prepared By: Er. Sudarshan Subedi


Constructors In Java-Parameterized Constructor
A constructor that has parameters is known as parameterized
constructor.
If we want to initialize fields of the class with our own values, then
use a parameterized constructor.

Prepared By: Er. Sudarshan Subedi


Constructors In Java-Parameterized Constructor

Prepared By: Er. Sudarshan Subedi


Java Inheritance

Inheritance is one of the key features


of OOP that allows us to create a new
class from an existing class.
The new class that is created is
known as subclass (child or derived
class) and the existing class from
where the child class is derived is
known as superclass (parent or base
class).
For inheritance in Java, extends
keyword is used.
We create an object of child class in
inheritance Prepared By: Er. Sudarshan Subedi
Java Inheritance

In Java, inheritance is an is-a relationship.


That is, we use inheritance only if there exists an is-a relationship
between two classes. For example,
• Bike is a Vehicle
• Apple is a Fruit
Here, Bike can inherit from Vehicle, Apple can inherit from Fruit
Note: Generally we use protected accesses specifier for members
that needs to be inherited.

Prepared By: Er. Sudarshan Subedi


Java Inheritance-Example

Prepared By: Er. Sudarshan Subedi


Java Inheritance-Example

Prepared By: Er. Sudarshan Subedi


Access Specifier For Java Inheritance
If we need to inherit any field on child class then that method must be
declared protected.

Prepared By: Er. Sudarshan Subedi


Multi-level Inheritance Example In Java

Prepared By: Er. Sudarshan Subedi


Multi-level Inheritance Example In Java

Prepared By: Er. Sudarshan Subedi


Construction Invocation Order in Inheritance (Multilevel Inheritance)

Note: Default Constructor of parent is


invoked first

Prepared By: Er. Sudarshan Subedi


Inheritance Example

Prepared By: Er. Sudarshan Subedi


Inheritance Example Contd..

Prepared By: Er. Sudarshan Subedi


Types of Inheritance

Prepared By: Er. Sudarshan Subedi


Multiple Inheritance in Java
Multiple inheritance in java is the capability of
creating a single class with multiple
superclasses.
Unlike some other popular object oriented
programming languages like C++, java
doesn’t provide support for multiple
inheritance in classes.
Java doesn’t support multiple inheritances in
classes because it can lead to diamond
problem
The problem occurs when methods with the
same signature exist in both the superclasses
and subclass. On calling the method, the It is creating an ambiguity because, we have 2
compiler cannot determine which class method parent classes which have the same identical
to be called method. So, which one to override? Java compiler
But multiple inheritance is supported in itself
Prepared By: Er. Sudarshan Subedi
comes to a confusion!
Multiple Inheritance in Java-Solution???

The solution to this problem of Multiple inheritance is using


Interface

Prepared By: Er. Sudarshan Subedi


Super Keyword in java

Super keyword refers to superclass (parent) objects.


It is used to call superclass methods, and to access the superclass
constructor.
The most common use of super keyword is to eliminate the confusion
between superclasses and subclasses that have methods with the same
name.

Prepared By: Er. Sudarshan Subedi


Super Keyword in java

Prepared By: Er. Sudarshan Subedi


Super Keyword
It is important to note that constructors in Java are not inherited.
Hence, there is no such thing as constructor overriding in Java.
The parent class constructor is always called before the subclass
constructor
However, we can call the constructor of the superclass from its
subclasses using super keyword which is required if superclass has
parameterized constructor

Prepared By: Er. Sudarshan Subedi


Super Keyword

Prepared By: Er. Sudarshan Subedi


Method Overloading in Java

In Java, two or more methods may have same name but differ in
parameters (different number of parameters, different types of
parameters, or both)
These methods are said to be overloaded methods and this feature is
called method overloading.
i.e. method overloading  same method name but different parameters
Method Overloading in Java-Example
Method Overloading in Java-Example
Constructor Overloading in Java
Similar to methods overloading in Java, we can also create two or more constructors
with different parameters. This is called constructor overloading.
Method Overriding in Java
If the same method is present in both the superclass and subclass, the
method in the subclass overrides the method in the superclass
We can use the @Override annotation to tell the compiler that we are
overriding a method. However, the annotation is not mandatory.
If an object of a parent class is used to invoke the method, then the
version in the parent class will be executed, but if an object of the
subclass is used to invoke the method, then the version in the child
class will be executed.
Java Overriding Rules:
• Both the superclass and the subclass must have the same method name, the same
return type and the same parameter list.
• We cannot override the method declared as final and static.
• We should always override abstract methods of the superclass
Prepared By: Er. Sudarshan Subedi
Method Overriding in Java Inheritance-Example

Prepared By: Er. Sudarshan Subedi


Access Specifiers in Method Overriding
The same method declared in the superclass and its subclasses can
have different access specifiers. However, there is a restriction.
We can only use those access specifiers in subclasses that provide
larger access than the access specifier of the superclass.
Suppose, a method myClass() in the superclass is declared protected.
Then, the same method myClass() in the subclass can be either public
or protected, but not private

Prepared By: Er. Sudarshan Subedi


Method Overriding-Calling super class’s method

Prepared By: Er. Sudarshan Subedi


Java Static Keyword

In Java, if we want to access class members without creating an


instance of class, we need to declare the class members static.
Static Methods
• Static methods are also called as class methods because those methods belong
to class rather than the object of a class.
• We can invoke static methods directly using the class name.
Java Static Keyword
Static Variables
• If we declare a variable static, all objects of the class share the same static
variable.
• It is because like static methods, static variables are also associated with the class.
• We do not need to create objects of the class to access the static variables.
Java Static Keyword-Accessing Static Variable and Methods
Final Keyword

Final keyword in Java is used as a non-access modifier to access that


can be used with variable, method or class.
Java final Variable
• In Java, we cannot change the value of a final variable.
• It is similar to creating constants in C
Java final Method
• In Java, the final method cannot be overridden by the child
class Java
Java final Class
• In Java, the final class cannot be inherited by another class

Prepared By: Er. Sudarshan Subedi


Abstraction in Java

Abstraction is the process of hiding the implementation details from the


user, only the functionality will be provided to the user.
In other words, the user will have the information on what the object
does instead of how it odes.
In Java, abstraction can be achieved using Abstract Classes and
Interfaces.
Real World Example: Making coffee with a coffee machine is a good
example of abstraction. You need to know how to use your coffee
machine to make coffee. The thing you don’t need to know is how the
coffee machine is working internally to brew a fresh cup of delicious
coffee. You don’t need to know the ideal temperature of the water or the
amount of ground coffee you need to use.
Prepared By: Er. Sudarshan Subedi
Abstraction In Java-Abstract Class

Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
A class which contains the abstract keyword in its declaration is known as
abstract class.
Abstract classes may or may not contain abstract methods
• An abstract method is a method without body
But, if a class has at least one abstract method, then the class must be
declared abstract.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, we have to inherit it from another class, provide
implementations to the abstract methods in it.
Prepared By: Er. Sudarshan Subedi
Abstraction In Java-Abstract Class-Summary

Prepared By: Er. Sudarshan Subedi


Abstraction In Java-Abstract Class-Example

Prepared By: Er. Sudarshan Subedi


Abstraction In Java-Abstract Class-Example

Create a class named AdderClass that has private fields firstName


and lastName, getters and setters for these fields, as well as abstract
methods named add, get, update, delete methods to add, update,
delete and get the data. Create two classes named TeacherClass and
StudentClass that inherits the AdderClass and has the defminition of
above abstract methods.

Prepared By: Er. Sudarshan Subedi


Abstraction In Java-Abstract Class-Example

Prepared By: Er. Sudarshan Subedi


Abstraction In Java-Abstract Class-Example

Prepared By: Er. Sudarshan Subedi


Abstraction In Java-Interfaces
Another way of achieving abstraction in Java is with Interfaces.
An interface in Java is a blueprint of a class.
It defines a set of methods that a class must implement.
There can be only abstract methods in the Java interface, not the
method body.
Interfaces specify what a class must do and not how. It is the blueprint
of the class.
Interface specifies a set of methods that the class has to implement.
To implement an interface, implements keyword is used.
Syntax:
public interface interface_name{
//declare constant fields
//declare methods that are abstract
Prepared By: Er. Sudarshan Subedi
Abstraction In Java-Interfaces
Like abstract classes, interfaces cannot be used to create objects
Interface methods do not have a body - the body is provided by the
"implement" class.
On implementation of an interface, we must override all of its
methods.
Interface methods are by default abstract and public.
Interface attributes are by default public, static and final.
An interface cannot contain a constructor (as it cannot be used to
create objects)

Prepared By: Er. Sudarshan Subedi


Abstraction In Java-Interfaces

Why use Interfaces?


It is used to achieve total abstraction.
Since java does not support multiple inheritances in the case of class,
by using an interface it can achieve multiple inheritances.
Any class can extend only 1 class but can any class implement infinite
number of interface.
It is also used to achieve loose coupling.
Interfaces are used to implement abstraction. So the question arises
why use interfaces when we have abstract classes? The reason is,
abstract classes may contain non-final variables, whereas variables in
the interface are final, public and static.
Prepared By: Er. Sudarshan Subedi
Abstraction In Java-Interfaces

Prepared By: Er. Sudarshan Subedi


Interface

Prepared By: Er. Sudarshan Subedi


Extending Interface
One Interface can also extend another interface as below:

Now any class that implements InterfaceB will have both the
implementation of both the methods.

Prepared By: Er. Sudarshan Subedi


Multiple Inheritance with Interface

 Multiple inheritance by interface occurs if a class implements


multiple interfaces (Approach 1) or also if an interface itself
extends multiple interfaces (Approach 2).
Approach 2 is preferred often than Approach 1.

Prepared By: Er. Sudarshan Subedi


Multiple Inheritance with Interface-Approach 1

Prepared By: Er. Sudarshan Subedi


Multiple Inheritance with Interface-Approach 2

Prepared By: Er. Sudarshan Subedi


Java Class vs Interface
Class Interface

The keyword used to create a class is “class” The keyword used to create an interface is “interface”

A class can be instantiated i.e., objects of a class can be created. An Interface cannot be instantiated i.e. objects cannot be created.

Classes do not support multiple inheritance. The interface supports multiple inheritance.

It can be inherited from another class. It cannot inherit a class.

It can be inherited by a class by using the keyword ‘implements’ and


It can be inherited by another class using the keyword ‘extends’.
it can be inherited by an interface using the keyword ‘extends’.

It can contain constructors. It cannot contain constructors.

It cannot contain abstract methods. It contains abstract methods only.

Variables and methods in a class can be declared using any access


All variables and methods in an interface are declared as public.
specifier(public, private, default, protected).

Variables in a class can be static, final, or neither. All variables are static and final.
Prepared By: Er. Sudarshan Subedi
Object Class In Java
Object class is present in java.lang package and class acts as a root
of inheritance hierarchy in any Java Program
Every class in Java is directly or indirectly derived from the Object
class.
If a Class does not extend any other class then it is direct child class
of Object and if extends other class then it is an indirectly derived.
Therefore the Object class methods are available to all Java classes.

Prepared By: Er. Sudarshan Subedi


Some Methods In Object Class

1. toString()
It provides string representation of an
Object
The default toString() method for class
Object returns a string consisting of the
name of the class of which the object is an
instance, the at-sign character `@’, and
the unsigned hexadecimal representation
of the hash code of the object
It is always recommended to override
toString() method to get our own String
representation of Object
Prepared By: Er. Sudarshan Subedi
Some Methods In Object Class

2. hashCode()
For every object, JVM generates a unique number
which is hashcode.
It returns distinct integers for distinct objects.
A common misconception about this method is that
hashCode() method returns the address of object,
which is not correct.
It convert the internal address of object to an integer by
using an algorithm
Override of hashCode() method needs to be done such
that for every object we generate a unique number.
For example, for a Student class we can return roll no.
of student from hashCode() method as it is unique.
Prepared By: Er. Sudarshan Subedi
Some Methods In Object Class

3. equals(Object Obj)
Compares the given object to “this” object (the
object on which the method is called).
It gives a generic way to compare objects for
equality.
It is recommended to override equals(Object obj)
method to get our own equality condition on
Objects.
It is generally necessary to override the
hashCode() method whenever this method is
overridden, so as to maintain the general contract
for the hashCode method, which states that equal
objects must have equal hash codes.
Prepared By: Er. Sudarshan Subedi
Some Methods In Object Class
4. getClass()
Returns the class object of “this” object and used
to get actual runtime class of the object
As it is final so we don’t override it.
5. finalize()
This method is called just before an object is
garbage collected.
It is called by the Garbage Collector on an object
when garbage collector determines that there are
no more references to the object.
We should override finalize() method to dispose
system resources, perform clean-up activities and
Prepared By: Er. Sudarshan Subedi
minimize memory leaks
Some Methods In Object Class

6. clone()
• It returns a new object that is exactly the same as this object
7. The remaining three methods wait(), notify() notifyAll() are related
to Concurrency

Prepared By: Er. Sudarshan Subedi


Java Polymorphism
The word polymorphism is a combination of two words
i.e. ploy and morphs.
The word poly means many and morphs means different forms.
In short, a mechanism by which we can perform a single action in
different ways.
Real life example
• A person in a shop is a customer, in an office, he is an employee, an the home he is
husband/ father/son, in a party he is guest. So, the same person possesses different
roles in different places. It is called polymorphism.

Prepared By: Er. Sudarshan Subedi


Java Polymorphism
We can achieve polymorphism in Java using the following ways:
1. Method Overriding
2. Method Overloading
3. Operator Overloading
• Some operators in Java behave differently with different operands.
• For example, + operator is overloaded to perform numeric addition as well as
string concatenation
• In languages like C++, we can define operators to work differently for different
operands.
• However, Java doesn't support user-defined operator overloading.

Prepared By: Er. Sudarshan Subedi


Java Polymorphism
There are two types of polymorphism in Java:
• Static Polymorphism (Compile Time Polymorphism): can be achieved
using method overloading
• Dynamic Polymorphism (Run Time Polymorphism): can be achieved
using method overriding

Prepared By: Er. Sudarshan Subedi


Dynamic Polymorphism/ Run Time Polymorphism/ Dynamic
Method Dispatch
Dynamic Polymorphism in OOPs is the mechanism by which multiple
methods can be defined with same name and signature in the superclass
and subclass.
The call to an overridden method are resolved at run time.
Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.
We can create a reference variable of super class that refer to a sub
class object as
SuperClassName referenceVariable = new SubClassName();
Example: Vehicle vehicle = new Bike();
where Vehicle is super class and Bike is sub class
ThisPrepared
is called upcasting
By: Er. Sudarshan Subedi
Dynamic Polymorphism/ Run Time Polymorphism/ Dynamic
Method Dispatch
If the reference variable of Parent class refers to the object of Child
class, it is known as upcasting.

Prepared By: Er. Sudarshan Subedi


Dynamic Method Dispatch Example

Create a class named Vehicle that has a method named wheels that
displays “Vehicle has wheels”. Similarly create two classes Bike and
Car that override the wheels method and display the number of wheels
respectively. Illustrate the concept of dynamic method dispatch/ runtime
polymorphism. Ask number from user. Call wheels of Bike if user
enters 1, that of Car if user enters 2 and that of vehicle if user enters
other numbers.

Prepared By: Er. Sudarshan Subedi


Dynamic Polymorphism-Example

Prepared By: Er. Sudarshan Subedi


Dynamic Polymorphism-Example
Output of Earlier Program

Prepared By: Er. Sudarshan Subedi


Binding in Java
Binding is a mechanism creating link between method call and
method actual implementation.
As per the polymorphism concept in Java , object can have many
different forms.
Object forms can be resolved at compile time and run time.
If linking between method call and method implementation is
resolved at compile time then we call it static binding/ early binding
If linking between method call and method implementation is
resolved at run time then it dynamic binding/late binding.

Prepared By: Er. Sudarshan Subedi


Differentiate Between Class(Concrete Class) and Abstract Class
Abstract Class Concrete Class

A concrete class is not declared using abstract


An abstract class is declared using abstract modifier.
modifier.

An abstract class cannot be directly instantiated A concrete class can be directly instantiated using
using the new keyword. the new keyword.

An abstract class may or may not contain abstract


A concrete class cannot contain an abstract method.
methods.

An abstract class cannot be declared as final. A concrete class can be declared as final.

Implement an interface is possible by not providing


Easy implementation of all of the methods in the
implementations of all of the interface’s methods.
interface.
For this a child class is needed..

Prepared By: Er. Sudarshan Subedi


Abstract Class vs Interface
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8,
abstract methods. it can have default and static methods also.

2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.
4) Abstract class can provide the implementation of Interface can't provide the implementation of abstract
interface. class.
5) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.
6) An abstract class can extend another Java class and An interface can extend another Java interface only.
implement multiple Java interfaces.

7) An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
8) A Java abstract class can have class members like Members of a Java interface are public by default.
private, protected, etc.
Prepared By: Er. Sudarshan Subedi
Class vs Interface
Class Interface

The keyword used to create a class is “class” The keyword used to create an interface is “interface”

A class can be instantiated i.e., objects of a class can be created. An Interface cannot be instantiated i.e. objects cannot be created.

Classes do not support multiple inheritance. The interface supports multiple inheritance

It can be inherited from another class. It cannot inherit a class.

It can be inherited by a class by using the keyword ‘implements’


It can be inherited by another class using the keyword ‘extends’.
and it can be inherited by an interface using the keyword ‘extends’.

It can contain constructors. It cannot contain constructors.

It cannot contain abstract methods. It contains abstract methods only.

Variables and methods in a class can be declared using any access


All variables and methods in an interface are declared as public.
specifier(public, private, default, protected).

Variables in a class can be static, final, or neither. All variables are static and final.
Prepared By: Er. Sudarshan Subedi

You might also like