Polimorfismo Java (con esempi)

In questo tutorial impareremo il polimorfismo di Java e la sua implementazione con l'aiuto di esempi.

Il polimorfismo è un concetto importante della programmazione orientata agli oggetti. Significa semplicemente più di una forma.

Ovvero, la stessa entità (metodo, operatore o oggetto) può eseguire operazioni diverse in scenari diversi.

Esempio: polimorfismo Java

 class Polygon ( // method to render a shape public void render() ( System.out.println("Rendering Polygon… "); ) ) class Square extends Polygon ( // renders Square public void render() ( System.out.println("Rendering Square… "); ) ) class Circle extends Polygon ( // renders circle public void render() ( System.out.println("Rendering Circle… "); ) ) class Main ( public static void main(String() args) ( // create an object of Square Square s1 = new Square(); s1.render(); // create an object of Circle Circle c1 = new Circle(); c1.render(); ) )

Produzione

 Rendering Square … Rendering Circle … 

Nell'esempio sopra, abbiamo creato una superclasse: Polygon e due sottoclassi: Square e Circle. Notare l'uso del render()metodo.

Lo scopo principale del render()metodo è rendere la forma. Tuttavia, il processo di rendering di un quadrato è diverso dal processo di rendering di un cerchio.

Quindi, il render()metodo si comporta in modo diverso nelle diverse classi. Oppure, possiamo dire che render()è polimorfico.

Perché il polimorfismo?

Il polimorfismo ci consente di creare codice coerente. Nell'esempio precedente, possiamo anche creare diversi metodi: renderSquare()e renderCircle()per renderizzare Square e Circle, rispettivamente.

Funzionerà perfettamente. Tuttavia, per ogni forma, dobbiamo creare metodi diversi. Renderà il nostro codice incoerente.

Per risolvere questo problema, il polimorfismo in Java ci consente di creare un unico metodo render()che si comporterà in modo diverso per forme diverse.

Nota : il print()metodo è anche un esempio di polimorfismo. Viene utilizzato per stampare i valori di tipo diverso come char, int, string, etc.

Possiamo ottenere il polimorfismo in Java utilizzando i seguenti modi:

  1. Sostituzione del metodo
  2. Metodo di sovraccarico
  3. Sovraccarico dell'operatore

Sostituzione del metodo Java

Durante l'ereditarietà in Java, se lo stesso metodo è presente sia nella superclasse che nella sottoclasse. Quindi, il metodo nella sottoclasse sovrascrive lo stesso metodo nella superclasse. Questo è chiamato override del metodo.

In questo caso, lo stesso metodo eseguirà un'operazione nella superclasse e un'altra operazione nella sottoclasse. Per esempio,

Esempio 1: polimorfismo che utilizza l'override del metodo

 class Language ( public void displayInfo() ( System.out.println("Common English Language"); ) ) class Java extends Language ( @Override public void displayInfo() ( System.out.println("Java Programming Language"); ) ) class Main ( public static void main(String() args) ( // create an object of Java class Java j1 = new Java(); j1.displayInfo(); // create an object of Language class Language l1 = new Language(); l1.displayInfo(); ) )

Uscita :

 Linguaggio di programmazione Java Common English Language

Nell'esempio precedente, abbiamo creato una superclasse denominata Language e una sottoclasse denominata Java. Qui, il metodo displayInfo()è presente sia in Language che in Java.

L'uso di displayInfo()è quello di stampare le informazioni. Tuttavia, sta stampando informazioni diverse in linguaggio e Java.

In base all'oggetto utilizzato per chiamare il metodo, vengono stampate le informazioni corrispondenti.

Lavorazione del polimorfismo Java

Nota : il metodo chiamato viene determinato durante l'esecuzione del programma. Pertanto, l'override del metodo è un polimorfismo di runtime .

2. Sovraccarico del metodo Java

In una classe Java, possiamo creare metodi con lo stesso nome se differiscono nei parametri. Per esempio,

 void func() (… ) void func(int a) (… ) float func(double a) (… ) float func(int a, float b) (… )

Questo è noto come sovraccarico del metodo in Java. In questo caso, lo stesso metodo eseguirà operazioni diverse in base al parametro.

Example 3: Polymorphism using method overloading

 class Pattern ( // method without parameter public void display() ( for (int i = 0; i < 10; i++) ( System.out.print("*"); ) ) // method with single parameter public void display(char symbol) ( for (int i = 0; i < 10; i++) ( System.out.print(symbol); ) ) ) class Main ( public static void main(String() args) ( Pattern d1 = new Pattern(); // call method without any argument d1.display(); System.out.println(""); // call method with a single argument d1.display('#'); ) )

Output:

 ********** ##########

In the above example, we have created a class named Pattern. The class contains a method named display() that is overloaded.

 // method with no arguments display() (… ) // method with a single char type argument display(char symbol) (… )

Here, the main function of display() is to print the pattern. However, based on the arguments passed, the method is performing different operations:

  • prints a pattern of *, if no argument is passed or
  • prints pattern of the parameter, if a single char type argument is passed.

Note: The method that is called is determined by the compiler. Hence, it is also known as compile-time polymorphism.

3. Java 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, and
  • operators like &, |, and ! are overloaded for logical and bitwise operations.

Let's see how we can achieve polymorphism using operator overloading.

The + operator is used to add two entities. However, in Java, the + operator performs two operations.

1. When + is used with numbers (integers and floating-point numbers), it performs mathematical addition. For example,

 int a = 5; int b = 6; // + with numbers int sum = a + b; // Output = 11

2. When we use the + operator with strings, it will perform string concatenation (join two strings). For example,

 String first = "Java "; String second = "Programming"; // + with strings name = first + second; // Output = Java Programming

Here, we can see that the + operator is overloaded in Java to perform two operations: addition and concatenation.

Note: In languages like C++, we can define operators to work differently for different operands. However, Java doesn't support user-defined operator overloading.

Polymorphic Variables

A variable is called polymorphic if it refers to different values under different conditions.

Object variables (instance variables) represent the behavior of polymorphic variables in Java. It is because object variables of a class can refer to objects of its class as well as objects of its subclasses.

Example: Polymorphic Variables

 class ProgrammingLanguage ( public void display() ( System.out.println("I am Programming Language."); ) ) class Java extends ProgrammingLanguage ( @Override public void display() ( System.out.println("I am Object-Oriented Programming Language."); ) ) class Main ( public static void main(String() args) ( // declare an object variable ProgrammingLanguage pl; // create object of ProgrammingLanguage pl = new ProgrammingLanguage(); pl.display(); // create object of Java class pl = new Java(); pl.display(); ) )

Output:

 I am Programming Language. I am Object-Oriented Programming Language.

Nell'esempio sopra, abbiamo creato una variabile oggetto pl della classe ProgrammingLanguage. Qui, pl è una variabile polimorfica. Questo è perché,

  • Nell'istruzione pl = new ProgrammingLanguage(), pl si riferisce all'oggetto della classe ProgrammingLanguage.
  • E, nell'istruzione pl = new Java(), pl si riferisce all'oggetto della classe Java.

Questo è un esempio di upcasting in Java.

Articoli interessanti...