Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Polymorphism

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 7

Polymorphism

Definition: The virtue by which the same action can be performed by


objects of different object classes and each responds in a different way
depending on its class is called Polymorphism.(Presenting the same
interface for different data types.)

Advantages of Polymorphism in Java

1. Increases code reusability by allowing objects of different classes to be treated as objects


of a common class.
2. Improves readability and maintainability of code by reducing the amount of code that
needs to be written and maintained.
3. Supports dynamic binding, enabling the correct method to be called at runtime, based on
the actual class of the object.
4. Enables objects to be treated as a single type, making it easier to write generic code that
can handle objects of different types.

Disadvantages of Polymorphism in Java

1. Can make it more difficult to understand the behavior of an object, especially if the code
is complex.
2. This may lead to performance issues, as polymorphic behavior may require additional
computations at runtime.

Generics in Java:
Generics means parameterized types. The idea is to allow type
(Integer, String, … etc., and user-defined types) to be a
parameter to methods, classes, and interfaces. Using Generics, it
is possible to create classes that work with different data
types. An entity such as class, interface, or method that operates
on a parameterized type is a generic entity.
Why Generics?
The Object is the superclass of all other classes, and Object
reference can refer to any object. These features lack type safety.
Generics add that type of safety feature. We will discuss that
type of safety feature in later examples.
Generics in Java are similar to templates in C++. For example,
classes like HashSet, ArrayList, HashMap, etc., use generics
very well. There are some fundamental differences between the
two approaches to generic types.
Types of Java Generics
Generic Method: Generic Java method takes a parameter and
returns some value after performing a task. It is exactly like a
normal function, however, a generic method has type parameters
that are cited by actual type. This allows the generic method to
be used in a more general way. The compiler takes care of the
type of safety which enables programmers to code easily since
they do not have to perform long, individual type castings.
Generic Classes: A generic class is implemented exactly like a
non-generic class. The only difference is that it contains a type
parameter section. There can be more than one type of
parameter, separated by a comma. The classes, which accept one
or more parameters, are known as parameterized classes or
parameterized types.

1 Parameter Passing in Argument:

// Java program to show working of user defined


// Generic classes

// We use < > to specify Parameter type


class Test<T> {
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}

// Driver class to test above


class Main {
public static void main(String[] args)
{
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String type


Test<String> sObj
= new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
}
}
Multiple Parameter Passing Argument:
// Java program to show multiple
// type parameters in Java Generics

// We use < > to specify Parameter type


class Test<T, U>
{
T obj1; // An object of type T
U obj2; // An object of type U

// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}

// To print objects of T and U


public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}

// Driver class to test above


class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj =
new Test<String, Integer>("GfG", 15);

obj.print();
}
}

Types of Polymorphism:
1. Ad-hoc Polymorphism, also called as Overloading Ad-hoc
Polymorphism allows functions having same name to act differently
for different types. For example: The + operator adds two integers and
concatenates two strings.
import java.util.*;

public class Main {


public static int sum(int x, int y)
{
int c = x + y;
return c;
}

public static String sum(String x, String y)


{
String summation = x.concat(y);
return summation;
}

public static void main(String[] args)


{
System.out.println(sum(50, 20)
+ " :- Integer addition Output");
System.out.println(
sum("Polymorphism", " achieved")
+ " :- String Concatenation Output");
}
}

1. Hence, by calling two different functions(which differ in the type of arguments)


having the same names, to execute multiple operations, we have successfully
achieved Ad-hoc Polymorphism.

2. Inclusion Polymorphism, also called as Subtyping Inclusion Polymorphism is the ability to


use derived classes through base class pointers and references. It is also known as Run-time
polymorphism because the address of the function is not located by the Compiler at compile-
time, rather, the right pointer from the virtual table is dereferenced to invoke the function at
run-time. The concept of Virtual Function, also known as Dynamic Linkage, is employed to
achieve Inclusion Polymorphism. The usage of Virtual Function allows the selection of that
function which is to be invoked based on the kind of object for which it is called. For example:
To implement such a Polymorphism technique, let us take different files under consideration
such as .jpg, .gif, .png files. All these files fall under the category of Image Files.
abstract class Animal {
abstract String talk();
}
class Cat extends Animal {
String talk() {
return "Meow!";
}
}
class Dog extends Animal {
String talk() {
return "Woof!";
} }
void letsHear(final Animal a) {
println(a.talk());
}
int main() {
letsHear(new Cat());
letsHear(new Dog());
}

3. Coercion Polymorphism, also called as Casting Coersion Polymorphism occurs when an object or
primitive is cast into some other type. It could be either Implicit or Explicit. Implicit casting happens as a
responsibility of Compiler itself. For example: float f=100 (integer implicitly gets promoted to float)
Explicit casting makes use of some type-casting expressions such as const_cast, dynamic_cast, etc. For
example: When a class defines conversion operator for some type, say “int”, then, it could be employed
anywhere in the program where integer type data is expected. Illustration Below could make it more
easier to understand:
class IntClass {
private int num;

public IntClass(int a) {
num = a;
}

public int intValue() {


return num;
} // conversion from User-defined type to Basic type
}

class Main {
public static void show(int x) {
System.out.println(x);
}

public static void main(String[] args) {


IntClass i = new IntClass(100);
show(746);
show(i.intValue());
}
}
4.Parametric Polymorphism, also called as Early Binding Parametric
Polymorphism opens a way to use the same piece of code for different types. It
is implemented by the use of Templates. For example: To develop an
understanding of this sort of polymorphism, let us execute a program for finding
greater of two Integers or two Strings,

You might also like