0% found this document useful (0 votes)
31 views26 pages

Java Polymorphism Notes

Java polymorphism notes

Uploaded by

fakeprathmesh123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
31 views26 pages

Java Polymorphism Notes

Java polymorphism notes

Uploaded by

fakeprathmesh123
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 26

Advanced Java Programming

Unit-I – Object Oriented Programming


By Prof. Zarrin Jalgaonkar
1. Polymorphism

1.1. What is Polymorphism?


Polymorphism is considered one of the important features of Object-Oriented Programming.
Polymorphism allows us to 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 the ability to take many forms.
Real-life Illustration Polymorphism: A person at the same time can have different characteristics. Like
a man at the same time is a father, a husband, and an employee. So, the same person possesses
different behavior in different situations. This is called polymorphism.

1.2. Types of Java polymorphism


In Java polymorphism is mainly divided into two types:
• Compile-time Polymorphism
• Runtime Polymorphism

• Compile-Time Polymorphism
Compile time polymorphism in Java is also known as early binding or static polymorphism. The binding is
performed during compilation time and hence the name compile-time polymorphism. Binding refers to
connecting the function call to the function body. It is achieved by overloading methods, and by changing
the signature of the function. The term signature of function refers to parameters and their types along
with the return value and its type. It defines the input and output of a function.
Example:
Overloading by passing different number of arguments
class CompileTime {
// perimeter method with a single argument
static int perimeter(int a) {
return 4 * a;
}
// perimeter method with two arguments (overloading)
static int perimeter(int l, int b) {
return 2 * (l + b);
}
}
class Polymorphism {
public static void main(String[] args) {
// calling perimeter method by passing a single argument
System.out.println("Side of square : 4\nPerimeter of square will be : " + Compiletime.perimeter(4) +
"\n");
// calling perimeter method by passing two arguments
System.out.println("Sides of rectangle are : 10, 13\nPerimeter of rectangle will be : " +
Compiletime.perimeter(10, 13));
}
}
Overloading by different types of argument to the function.
class Compiletime{
// contact method, which takes two arguments String and long
static void contact(String fname, long number) {
System.out.println("Name : "+fname+"\nNumber : "+number);
}
// contact method, which takes two arguments and both are Strings (overloading)
static void contact(String fname, String mailid) {
System.out.println("Name : "+fname+"\nEmail : "+mailid);
}
}
class Polymorphism{
public static void main(String[] args) {
// calling first contact method
Compiletime.contact("Soham", 1234567890);
System.out.print("\n");
// calling second contact method
Compiletime.contact("Soham", "soham@mail.com");
}
}

• Runtime Polymorphism
Runtime polymorphism is also called dynamic method dispatch. Instead of resolving the overridden
method at compile-time, it is resolved at runtime. Here, an overridden child class method is called
through its parent's reference. Then the method is called according to the type of object. In runtime, JVM
figures out the object type and the method belonging to that object.

Runtime polymorphism in Java occurs when we have two or more classes, and all are interrelated through
inheritance. To achieve runtime polymorphism, we must build an "IS-A" relationship between classes and
override a method.
Method overriding
If a child class has a method as its parent class, it is called method overriding. If the derived class has a
specific implementation of the method that has been declared in its parent class is known as method
overriding.
Rules for overriding a method in Java:

• There must be inheritance between classes.


• The method between the classes must be the same (name of the class, number, and type of
arguments must be the same).
• Final methods cannot be overridden.
• Static methods cannot be overridden (MethodOverridingvs.MethodHiding).
• Private methods cannot be overridden.
• We cannot override constructor as parent and child class can never have constructor with same
name (Constructor name must always be same as Class name).
• Abstract methods in an interface or abstract class are meant to be overridden in derived concrete
classes otherwise compile-time error will be thrown.
Example: Animal class
//parent class Animal
class Animal{
// creating place method
void place(){
System.out.println("Animals live on earth.");
}
}
// Dog class extends Animal class
class Dog extends Animal{
// overriding place method
void place(){
System.out.println("Dog lives in kennel.");
}
}
// Horse class extends Animal class
class Horse extends Animal{
// overriding place method
void place(){
System.out.println("Horse lives in stable.");
}
}
// Rabbit class extends Animal class
class Rabbit extends Animal{
// overriding place method
void place(){
System.out.println("Rabbit lives in burrow.");
}
}
class Polymorphism{
public static void main(String[] args) {
// creating object of Animal class
Animal A = new Animal();
A.place();
A = new Dog();
A.place();
A = new Horse();
A.place();
A = new Rabbit();
A.place();
}
}
Output:
Animals live on earth.
Dog lives in kennel.
Horse lives in stable.
Rabbit lives in burrow.

2. Abstract and concrete classes


What is a Concrete Class?
A concrete class in java is a class that has all its methods implemented. For any class to be classified as
concrete, it cannot have any unimplemented methods. Concrete classes can extend abstract class in Java
or implement interfaces, but they must implement all the methods of the abstract class or interface they
inherit. We can create an object of concrete class using the new keyword.
A concrete class is an abstract class if it has even one abstract method, i.e. an unimplemented method
because it doesn't meet the condition of being a concrete class.
Concrete classes implement all methods and, in most cases, they inherit an abstract class or implement
an interface. Java's final class is a class that cannot be inherited, so it's possible to declare concrete classes
as final classes. As a concrete class inherits or implements all the methods from an abstract class or an
interface, it can also be called a 100% implemented class in Java. Java methods from concrete classes are
inherited or completely implemented from abstract classes or interfaces.
Simple Concrete Class Example:
class ConcreteCalculator {
//Concrete calculator class to perform arithmetic operations.
static int add(int a, int b)
{
//this method calculates the sum of two numbers
return a + b;
}
static int subtract(int a, int b)
{
//this method calculates the difference between two numbers
return a - b;
}

static int multiply(int a, int b)


{
//this method calculates product of two numbers
return a * b;
}
static int divide(int a, int b)
{
//this method calculates the division of two numbers
return a / b;
}
public static void main(String[] args)
{
//Main method
int sum = add(100, 154); //Calls method add and stores result
int diff = subtract(154, 79); //Calls method subtract and stores result
int prod = multiply(7, 8); //Calls method multiply and stores result
int div = divide(345, 5); //Calls method divide and stores result

//Print results of all the operations


System.out.println("Addition result: " + sum);
System.out.println("Subtraction result: " + diff);
System.out.println("Multiplication result: " + prod);
System.out.println("Division result: " + div);
}
}
Output:
Addition result: 254
Subtraction result: 75
Multiplication result: 56
Division result: 69
Abstraction in Java:
Abstraction is a process of hiding implementation and showing only essential details to the user.
Abstraction is used in the case of banking applications to hide crucial details from end-users.

Abstract Class in Java:


• Abstract class in java is a class that is declared using the abstract keyword.
• It contains abstract methods which means it has incomplete or unimplemented methods.
• Abstract classes can have abstract as well as non-abstract methods.
• We cannot create objects of an abstract class to use abstract class methods abstract class needs to be
inherited.
Program:
Let's consider a scenario. The shape is an abstract class with two unimplemented methods area(),
perimeter(). The other three classes extend class Shape and implement both the methods area() and
perimeter() of the abstract class. Hence, the classes Circle, Triangle, and Square are concrete classes.
// Java program in which concrete classes extend abstract class
abstract class Shape{
//Declaring abstract class shape
abstract double area(); // unimplemented method area
abstract double perimeter(); //unimplemented method perimeter
}
class Circle extends Shape //Declaring class Circle that extends class Shape
{
//Declaring required varibles
double r = 5; //radius of circle
public double area()
{
//Implementing parent class method area
return 3.14 * r * r; //Area of Circle = π r^2
}
public double perimeter()
{
//Implementing parent class method perimeter
return 2 * 3.14 * r; //Perimeter of Circle = 2 π r
}
}
class Triangle extends Shape //Declaring class Triangle that extends class Shape
{
//Declaring required variables
double a = 5; //side of triangle
double b = 12; //base of triangle
double c = 9; // side of triangle
double h = 4; //height of traingle
public double area()
{
//Implementing parent class method area
return b * h / 2; //Area of traingle = ½ × Base × Height
}
public double perimeter()
{
//Implementing parent class method perimeter
return a + b + c; //Perimeter of triangle = a + b + c (Sum of all sides)
}
}
class Square extends Shape //Declaring class Square that extends class Shape
{
//Declaring required variables
double a = 8; //side of square
public double area()
{
//Implementing parent class method area
return a * a; //Area of Square = a * a (side square)
}
public double perimeter()
{
//Implementing parent class method perimeter
return 4 * a; //Perimeter of Square = 4 * side (Sum of all sides)
}
}
public class DemoMain {
public static void main(String[] args) {
//Creating objects of concrete class circle
Circle c = new Circle();
//calling methods of concrete class circle
double c_area = c.area();
double c_perimeter = c.perimeter();
System.out.println("Area of Circle: " + c_area);
System.out.println("Perimeter of Circle: " + c_perimeter);
//Creating objects of concrete class triangle
Triangle t = new Triangle();
//calling methods of concrete class triangle
double t_area = t.area();
double t_perimeter = t.perimeter();
System.out.println("Area of Triangle: " + t_area);
System.out.println("Perimeter of Triangle: " + t_perimeter);
//Creating objects of concrete class square
Square s = new Square();
//calling methods of concrete class square
double s_area = s.area();
double s_perimeter = s.perimeter();
System.out.println("Area of Square: " + s_area);
System.out.println("Perimeter of Square: " + s_perimeter)
}
}
Output:
Area of Circle: 78.5
Perimeter of Circle: 31.400000000000002
Area of Triangle: 24.0
Perimeter of Triangle: 26.0
Area of Square: 64.0
Perimeter of Square: 32.0

What is an Interface?

• Interface in Java is a mechanism used to achieve abstraction.


• Interface is said to be a blueprint of a class. It contains only abstract methods and variables.
• Interface doesn't have a method body.
• Interface is used to achieve abstraction. It can also be used to implement multiple inheritances.
Program:
// Java program to illustrate concrete class
// This is an interface
interface DemoInterface {
int product(int a, int b);
int sum(int a, int b);
}
// This is an abstract class that implements interface
abstract class DemoAbstract implements DemoInterface {
// this method calculates product of two numbers
public int product(int a, int b)
{
return a * b;
}
}
// This is a concrete class that extends abstract class
class DemoConcrete extends DemoAbstract {
// this method calculates
// sum of two numbers
public int sum(int a, int b)
{
return a + b;
}
// main method
public static void main(String args[])
{
DemoConcrete obj = new DemoConcrete();
int p = obj.product(19, 16);
int s = obj.sum(1155, 190);
// print product
System.out.println("Product: " + p);
// print sum
System.out.println("Sum: " + s);
}
}
Output:
Product: 304
Sum: 1345

Abstract Class Concrete Class


Abstract class can have unimplemented methods. Concrete class cannot have unimplemented
methods.
Abstract class cannot be instantiated i.e. we cannot Concrete class in java can be instantiated i.e. we can
create an object of an abstract class. create an object of an abstract class using the new
keyword.
We can declare an abstract class using the abstract Declaration of a concrete class is the same as of any
keyword. normal class in java using the class keyword.
It is impossible to create an abstract class without On the other hand, concrete class in java should not
incomplete methods as an abstract class without have a single incomplete method.
any abstract method will be a normal java class.
Abstract class cannot be declared as a final class. Concrete class can be declared as a final class as
The reason is final class cannot be inherited and they have implementation for all the methods and
abstract classes are meant to be inherited and then need not be inherited.
used.
Abstract class should have abstract methods. A concrete class implements all the
abstract(unimplemented) methods of its parent
abstract class.

3. Final Methods and classes


Final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to a
variable, a method, or a class. The following are different contexts where final is used.

Characteristics of final keyword in java:


In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or
extended. Here are some of its characteristics:
Final variables: When a variable is declared as final, its value cannot be changed once it has been
initialized. This is useful for declaring constants or other values that should not be modified.
Final methods: When a method is declared as final, it cannot be overridden by a subclass. This is useful
for methods that are part of a class’s public API and should not be modified by subclasses.
Final classes: When a class is declared as final, it cannot be extended by a subclass. This is useful for
classes that are intended to be used as is and should not be modified or extended.
Initialization: Final variables must be initialized either at the time of declaration or in the constructor of
the class. This ensures that the value of the variable is set and cannot be changed.
Performance: The use of final can sometimes improve performance, as the compiler can optimize the
code more effectively when it knows that a variable or method cannot be changed.
Security: final can help improve security by preventing malicious code from modifying sensitive data or
behavior.
Overall, the final keyword is a useful tool for improving code quality and ensuring that certain aspects of
a program cannot be modified or extended. By declaring variables, methods, and classes as final,
developers can write more secure, robust, and maintainable code.

Final Variables
When a variable is declared with the final keyword, its value can’t be modified, essentially, a constant.
This also means that you must initialize a final variable. If the final variable is a reference, this means that
the variable cannot be re-bound to reference another object, but the internal state of the object pointed
by that reference variable can be changed i.e. you can add or remove elements from the final array or
final collection. It is good practice to represent final variables in all uppercase, using underscore to
separate words.
We must initialize a final variable, otherwise, the compiler will throw a compile-time error. A final variable
can only be initialized once, either via an initializer or an assignment statement. There are three ways to
initialize a final variable:
You can initialize a final variable when it is declared. This approach is the most common. A final variable
is called a blank final variable if it is not initialized while declaration.
A blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you
have more than one constructor in your class then it must be initialized in all of them, otherwise, a
compile-time error will be thrown.
A blank final static variable can be initialized inside a static block.
Let us see these two different ways of initializing a final variable:
// Java Program to demonstrate Different Ways of Initializing a final Variable
// Main class
class GFG {
final int THRESHOLD = 5; // a final variable direct initialize
final int CAPACITY; // a blank final variable
final int MINIMUM; // another blank final variable
static final double PI = 3.141592653589793; // a final static variable PI direct initialize
static final double EULERCONSTANT; // a blank final static variable
// instance initializer block for initializing CAPACITY
{
CAPACITY = 25;
}
// static initializer block for initializing EULERCONSTANT
static{
EULERCONSTANT = 2.3;
}
// constructor for initializing MINIMUM
// Note that if there are more than one constructor, you must initialize MINIMUM in them also
public GFG()
{
MINIMUM = -1;
}
}
When to use a final variable?
The only difference between a normal variable and a final variable is that we can re-assign the value to a
normal variable but we cannot change the value of a final variable once assigned. Hence final variables
must be used only for the values that we want to remain constant throughout the execution of the
program.
Example 1:
// Java Program to Demonstrate Re-assigning final Variable will throw Compile-time Error
// Main class
Class Main {
// Declaring and customly initializing static final variable
static final int CAPACITY = 4;
// Main driver method
public static void main(String args[])
{
// Re-assigning final variable will throw compile-time error
CAPACITY = 5;
}
}
4. Creating and using Interfaces
What is an Interface?
An Interface in Java programming language is defined as an abstract type used to specify the behavior of a
class. A Java interface contains static constants and abstract methods. A class can implement multiple
interfaces. In Java, interfaces are declared using the interface keyword. All methods in the interface are
implicitly public and abstract.
We will define an interface using the interface keyword as shown below −
interface MyInterface{
public void display();
public void setName(String name);
public void setAge(int age);
}
Purpose of the interface

• Provides communication: One of the uses of the interface is to provide communication. Through
interface you can specify how you want the methods and fields of a particular type.
• Multiple inheritance: Java doesn’t support multiple inheritance, using interfaces you can achieve
multiple inheritance
• Abstraction: Abstraction is a 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 does it. Since all the methods of the interface are abstract and user
doesn’t know how a method is written except the method signature/prototype. Using interfaces, you
can achieve (complete) abstraction.
• Loose coupling: Coupling refers to the dependency of one object type on another, if two objects are
completely independent of each other and the changes done in one doesn’t affect the other both are
said to be loosely coupled.
Example 1:
public interface Vehicle {
public void start();
public void stop();
}
class Car implements Vehicle {
public void start() {
System.out.println("starting car engine...");
}
public void stop() {
System.out.println("stopping car engine...");
}
}
class Truck implements Vehicle {
public void start() {
System.out.println("starting truck engine...");
}
public void stop() {
System.out.println("stopping truck engine...");
}
}
public class InterfaceExample {
public static void main(String[] args)
{
Vehicle tesla = new Car();
tesla.start();
tesla.stop();
Vehicle tata = new Truck();
tata.start();
tata.stop();
}
}
Example 2: Loose Coupling
interface Keyboard
{
String display();
}
class DellKeyboard implements Keyboard
{
String info;
public String display()
{
this.info = "the Dell keyboard.";
return this.info;
}
}
class LenovoKeyboard implements Keyboard
{
String info;
public String display()
{
this.info = "the Lenovo keyboard.";
return this.info;
}
}
class Computer
{
// the method is now dependent on the interface Keyboard
public void keyboardUsed(Keyboard k)
{
System.out.println("The computer is using " + k.display());
}
}
public class CouplingExample
{
// main method
public static void main(String args[])
{
// creating an object of the class Computer
Computer obj = new Computer();
// creating an object of the class LenovoKeyboard
LenovoKeyboard lk = new LenovoKeyboard();
obj.keyboardUsed(lk);

// creating an object of the class DellKeyboard


DellKeyboard dk = new DellKeyboard();
obj.keyboardUsed(dk);
}
}

Example 3: The Java program that demonstrates multiple interfaces is shown below.
//Interface_One declaration
interface Interface_One{
void print();
}
//Interface_Two declaration
interface Interface_Two{
void show();
}
//multiple inheritance - DemoClass implementing Interface_One and Interface_Two
class DemoClass implements Interface_One,Interface_Two{
public void print(){ //Override Interface_One print()
System.out.println("Democlass::Interface_One_Print ()");
}
public void show(){ //Override Interface_Two show()
System.out.println("DemoClass::Interface_Two_Show ()");
}
}
public class Main{
public static void main(String args[]){
DemoClass obj = new DemoClass(); //create DemoClass object and call methods
obj.print();
obj.show();
}
}
Example 4: The Java program to implement interface inheritance is shown below.
//Interface_One declaration
interface Interface_One{
void print();
}
//Interface_Two declaration; inherits from Interface_One
interface Interface_Two extends Interface_One{
void show();
}
//multiple inheritance - DemoClass implementing Interface_Two
class DemoClass implements Interface_Two{
public void print(){ //Override Interface_Two print()
System.out.println("Democlass
public class Main{
public static void main(String args[]){
DemoClass obj = new DemoClass(); //create DemoClass object and call methods
obj.print();
obj.show();
}
}
Lab Work
Program 1. Overloading by changing the number of parameters in the argument
class MethodOverloading {
// overloading of method which takes single int object as a parameter
private static void display(int a){
System.out.println("One Arguments: " + a);
}
// method which takes two object or parameters
private static void display(int a, int b){
System.out.println("Two Arguments: " + a + " and " + b);
}
// main method
public static void main(String[] args) {
// calling display function by passing one parameter: method 1 is called
display(2);
// calling display function by passing two parameter: method 2 is called
display(2, 4);
}
}
Program 2. By changing Datatype of parameter
class MethodOverloading {
// this method accepts int datatype
private static void display(int a){
System.out.println("Got Int data.");
}
// this method accepts String object
private static void display(String a){
System.out.println("Got String object.");
}
public static void main(String[] args) {
display(4);
display("Hello");
}
}
Program 3. By changing the sequence of parameters
class Student{
// Method 1
public void stuIdentity(String name, int id)
{
// Printing name and id of student
System.out.println("stuName :" + name + " " + "Id :" + id);
}
// Method 2
public void stuIdentity(int id, String name)
{
// Again printing name and id of person
System.out.println("Id :" + id + " "+ "stuName :" + name);
}
}
// Class 2
// Main class
class Main {
// Main driver method
public static void main(String[] args)
{
// Creating object of above class
Student stu= new Student(); // Passing name and id // Reversing order
stu.stuIdentity("Mohit", 1);
stu.stuIdentity(2, "shubham");
}
}
Program 3. Overriding example1
// parent class Shape
class Shape{
// creating area method
void area(){
System.out.println("Formula for areas.");
}
}
// Square class extends Shape class
class Square extends Shape{
// overriding area method
void area(){
System.out.println("Area of square : a * a");
}
}
// Rectangle class extends Shape class
class Rectangle extends Shape{
// overriding area method
void area(){
System.out.println("Area of rectangle : 2 * (a + b)");
}
}
// Circle class extends Shape class
class Circle extends Shape{
// overriding area method
void area(){
System.out.println("Area of circle : pi * r * r");
}
}
class Polymorphism{
public static void main(String[] args) {
// creating new object of Shape class
Shape S = new Shape();
S.area();
S = new Square();
S.area();
S = new Rectangle();
S.area();
S = new Circle();
S.area();
}
}
Program 4. Overriding example2
// parent class Bank
class Bank{
// creating rateOfInterest method
float rateOfInterest(){
return 0;
}
}
// ICICI class extends Bank class
class ICICI extends Bank{
// overriding rateOfInterest method
float rateOfInterest(){
return 5.5f;
}
}
// SBI class extends Bank class
class SBI extends Bank{
// overriding rateOfInterest method
float rateOfInterest(){
return 10.6f;
}
}
// HDFC class extends Bank class
class HDFC extends Bank{
// overriding rateOfInterest method
float rateOfInterest(){
return 9.4f;
}
}
class Polymorphism{
public static void main(String[] args) {
// creating variable of Bank class
Bank B;
B = new ICICI();
System.out.println("Rate of interest of ICICI is:"+B.rateOfInterest());
B = new SBI();
System.out.println("Rate of interest of SBI is: "+B.rateOfInterest());
B = new HDFC();
System.out.println("Rate of interest of HDFC is: "+B.rateOfInterest());
}
}
Program 5. Implementation of Abstract Class
//Example of an abstract class that has abstract and non-abstract methods
abstract class Bike{
Bike()
{
System.out.println("bike is created");
}
abstract void run(); //abstract method that need to be overriden
void changeGear() //non-abstract method
{
System.out.println("gear changed");
}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run()
{
System.out.println("Bike running safely..");
}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Program 6. Implementation of Interface
import java.io.*;
interface Vehicle {
// all are the abstract methods.
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}
class Bicycle implements Vehicle{
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}
// to decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}
public void printStates() {
System.out.println("speed: " + speed + " gear: " + gear);
}
}
class Bike implements Vehicle {
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}
// to decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}
public void printStates() {
System.out.println("speed: " + speed + " gear: " + gear);
}
}
class Main {
public static void main (String[] args) {
// creating an instance of Bicycle doing some operations
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);
System.out.println("Bicycle present state :");
bicycle.printStates();

// creating instance of the bike.


Bike bike = new Bike();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);

System.out.println("Bike present state :");


bike.printStates();
}
}

inprotected.com

You might also like