0% found this document useful (0 votes)
155 views21 pages

POLYMORPHISM

Polymorphism allows objects to take on multiple forms. There are two types of polymorphism in Java: compile-time polymorphism which occurs during method overloading, and runtime polymorphism which occurs during method overriding. Method overriding provides specific implementation of a method declared in the parent class, while method overloading involves methods with the same name but different parameters within a class.

Uploaded by

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

POLYMORPHISM

Polymorphism allows objects to take on multiple forms. There are two types of polymorphism in Java: compile-time polymorphism which occurs during method overloading, and runtime polymorphism which occurs during method overriding. Method overriding provides specific implementation of a method declared in the parent class, while method overloading involves methods with the same name but different parameters within a class.

Uploaded by

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

UNIT-3

POLYMORPHISM:- Polymorphism came from the two GreeK words poly means
many and morphs meaning forms. The ability to exit in different forms is called polymorphism.
In java a variable an object or a method can exit in different forms, this performing various task
depending on the context.

There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

If you overload a static method in Java, it is the example of compile time polymorphism.

Runtime Polymorphism in Java


The polymorphism exhibited at runtime is called dynamic polymorphism. This means when a
method is called, the method all is bound to the method boy at the time of running the
program, dynamically.

Method signature:-

Java Runtime Polymorphism Example: Shape


class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Write a program to create Sample class which contains two methods with the same name
but with different signatures.

Class Sample

void add(int a, int b) // method to add two values

System.out.println(“sum of two vaues is ”+(a+b));

void add(int a, int b, int c) // method to add three values

System.out.println(“the sum of three numbrs is”+(a+b+c));

class Poly

Public static void main(String args[])

Sample s=new Sample(); //create a sample class object


s.add(10,20);

s.add(30,40,50);

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is
already provided by its super class.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Ex. Write a java program for overriding


Class One
{
//method to calaculate square values
Void calculate(double x)
{
System.out.println(“the square value is ”+(x*x));
}
}
Class Two extends One
{
//method to calculate square root value
Void calculate(double x)
{
System.out.println(“the square root is ”+Math.sqrt(x));
}
}
Class Poly
{
Public static void main(String args[])
{
//create sub class object t
Two t=new Two();
t.calculate(25);
}
}
Difference between method overloading and method overriding in java

There are many differences between method overloading and method overriding in java. A list
of differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

1) Method overloading is used to Method overriding is


increase the readability of the used to provide the
program. specific implementation of
the method that is
already provided by its
super class.

2) Method overloading is Method overriding


performed within class. occurs in two classes that
have IS-A (inheritance)
relationship.

3) In case of method In case of method


overloading, parameter must overriding, parameter
be different. must be same.

4) Method overloading is the Method overriding is the


example of compile time example of run time
polymorphism. polymorphism.

5) In java, method overloading Return type must be same


can't be performed by or covariant in method
changing return type of the overriding.
method only. Return type can
be same or different in method
overloading. But you must
have to change the parameter.

Static polymorphism:-The polymorphism exhibited at the compilation is called static


polymorphism. Here the java compiler knows without any ambiguity which method is called at the time
of compilation.

Polymorphism with static method:-static method is a method whose single copy in memory is shared by
all the objects of the class.

class One

static void calculate(double x)

System.out.println(“”+(x*x));

Class Two extends One

static void calculate(double x)

System.out.println(“square root of x is ”+Math.sqrt(x));

}
}

class Poly

Public static void main(String args[])

One o=new Two();

o.calculate(25);

Polymorphism with Private Methods:-


Private methods are the methods which are declared by using the access specifier ‘private’. This access
specifier makes the method non available outside the class. So other programmers cannot access the
private methods.

Polymorphism with Final methods


Methods which are declared as final are called final methods. Final methods cannot be overridden,
because they are not available to the sub class. Therefore , only method overloading is possible with
final methods.

There are two uses of declaring a method as final

1.when a method is declared as final, the performance will be better.

2. when the programmer does not want others to override his method, he should declare his method as
final.

Ex. Program for polymorphism with final methods


class A

final void method()

System.out.println(“Hello”);

}
class B

void method2()

A.method1();

Final class:-
A final class is a class which is declared as final. Final keyword before class prevents inheritance. This
means sub classes can not be created to a final class.

In two case the final keyword is used:


1. It is used to declare constants
Ex:- PI=3.14159
2. It is used to prevent inheritance
Ex:- final class B extends A // this is invalid statement in java

Type Casting in Java


In Java, type casting is a method or process that converts a data type into another data type in
both ways manually and automatically. The automatic conversion is done by the compiler and
manual conversion performed by the programmer. In this section, we will discuss type
casting and its types with proper examples.

Type casting: Convert a value from one data type to another data type is known
as type casting.

Types of Type Casting


There are two types of type casting:

o Widening Type Casting


o Narrowing Type Casting
Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no
chance to lose data. It takes place when:

o Both data types must be compatible with each other.


o The target type must be larger than the source type.

1. byte -> short -> char -> int -> long -> float -> double

For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other.

Example: Widening TypeCasting.java

public class WideningTypeCasting


{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}

Narrowing Type Casting


Narrowing Type casting :- Converting a higher data type into a lower one is
called narrowing type casting. It is also known as explicit conversion or casting up. It is done
manually by the programmer. If we do not perform casting then the compiler reports a compile-
time error.

1. double -> float -> long -> int -> char -> short -> byte

In the following example, we have performed the narrowing type casting two times. First, we
have converted the double type into long data type after that long data type is converted into
int type.
Ex:- write a java program for NarrowingTypeCasting

public class NarrowingTypeCasting


{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}

INTERFACE IN JAVA
An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple
inheritance in java.

In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods
declared in the interface.

Syntax: interface <interface_name>

// declare constant fields


// declare methods that abstract
// by default.
}

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is provided
in the Demo class.

interface printable{
void print();
}
class Demo implements printable
{
public void print(){System.out.println("Hello");
}
public static void main(String args[]){
Demo obj = new Demo();
obj.print();
}
}

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritances.

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}

Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package


The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:
1. javac -d directory javafilename

For example

1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep
the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The
represents the current folder.

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to
the current package.

Example of package that import the packagename.*


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

1. Subpackage in java
2. Package inside the package is called the subpackage. It should be created to categorize
the package further.
3. Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc. These classes
represent a particular group e.g. Reader and Writer classes are for Input/Output
operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has
subcategorized the java package into subpackages such as lang, net, io etc. and put the
Input/Output related classes in io package, Server and ServerSocket classes in net
packages and so on.

Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[]){
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java

To Run: java com.javatpoint.core.Simple

Output:Hello subpackage

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

ADVANTAGES OF EXCEPTION HANDLING:-The core advantage of exception handling


is to maintain the normal flow of the application. An exception normally disrupts the normal
flow of the application; that is why we need to handle exceptions. Let's consider a scenario:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions
are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or
finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide
the exception handling code so that the normal flow of the program can be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers' fault that he is not
checking the code before it being used.

Syntax of Java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }

Java Exception Handling Example


Ex:- example of Java Exception Handling in which we are using a try-catch statement to handle
the exception.

JavaExceptionDemo.java

public class JavaExceptiondEMO{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Advantage of Java throws keyword

Java throws Example


Let's see the example of Java throws clause which describes that checked exceptions can be
propagated by throws keyword.

Testthrows1.java

1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }

Difference between throw and throws in Java


The throw and throws is the concept of exception handling where the throw keyword throw the
exception explicitly from a method or a block of code whereas the throws keyword is used in
signature of the method.

There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:

Sr. Basis of throw throws


no. Differences

1. Definition Java throw Java throws


keyword is keyword is used
used throw an in the method
exception signature to
explicitly in declare an
the code, exception which
inside the might be thrown
function or by the function
the block of while the
code. execution of the
code.
2. Type of exception Using throws
Using throw keyword, we
keyword, we can can declare
only propagate both checked
unchecked and
exception i.e., the unchecked
checked exception exceptions.
cannot be However, the
propagated using throws
throw only. keyword can
be used to
propagate
checked
exceptions
only.

3. Syntax The throw The throws


keyword is keyword is
followed by followed by class
an instance of names of
Exception to Exceptions to be
be thrown. thrown.

4. Declaration throw is used throws is used


within the with the method
method. signature.

5. Internal We are We can declare


implementation allowed to multiple
throw only exceptions using
one exception throws keyword
at a time i.e. that can be
we cannot thrown by the
throw multiple method. For
exceptions. example, main()
throws
IOException,
SQLException.

Java throw Example


TestThrow.java

public class TestThrow {


//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Example of abstract class

1. abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method

1. abstract void printStatus(); //no method body and abstract

Example of Abstract class that has an abstract method


The below example shows, Bike is an abstract class that contains only one abstract method run.
Its implementation is provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Another real scenario of abstract class
The abstract class can also be used to provide some implementation of the interfaces.

In such case, the end user may not be forced to override all the methods of the interface.

Note: If you are beginner to java, learn interface first and skip this example.
1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }
26. }

Output:I am a
I am b
I am c
I am d

You might also like