Java >> Tutoriel Java >  >> Java

Polymorphisme en Java avec exemple

Prérequis :Remplacement de méthode en Java

Comme nous le savons,
En Java, nous avons le concept d'héritage, les fonctionnalités de la classe parent peuvent être héritées/étendues à la classe enfant, en utilisant ce concept, nous pouvons comprendre, qu'est-ce que le remplacement de méthode en Java ? Nous avons déjà vu l'exemple de redéfinition de méthode dans cet article :Inheritance in Java with Example. Nous avons discuté du fait que les méthodes avec des membres de données privées ne peuvent pas être remplacées, nous revenons au même exemple et discutons de l'utilisation de Super Keyword.

Considérez le programme :

import java.util.Scanner;
class Headquarters
{
	int totalemployees; // Data Member 1
	String cityname; // Data Member 2
	Scanner KB=new Scanner(System.in);
	void getDetails()
	{
		System.out.println("Enter City Where Headquarters is Sitiuated :");
		cityname=KB.nextLine();
		System.out.println("Enter Total Number of Employees in Headquarters");
		totalemployees=KB.nextInt();
	}
	void showDetails()
	{
		System.out.println("Company Headquarters is Sitiuated in "+cityname+" and has "+totalemployees+" Employees");
	}
}

class Mainbranch extends Headquarters
{	
	int totalMBemployees;
	String citynameMB;
	
	void getDetails()
	{  
		System.out.println("Headquarters:");
		super.getDetails();
		System.out.println("Main Branch:");
		System.out.println("Enter City Where Main Branch is Sitiuated");
		KB.nextLine();//to understand why we used this statement visit my first article at this LINK
		citynameMB=KB.nextLine();
		System.out.println("Enter The Total Number of Employees In Main Branch");
		totalMBemployees=KB.nextInt();
	}
	
	void showDetails()
	{	
		System.out.println("Headquarters:");
		super.showDetails();
		System.out.println("Main Branch:");
		System.out.println("Company Main Branch is Sitiuated in "+citynameMB+" and has "+totalMBemployees+" Employees");
	}
}

class Company
{
	public static void main(String args[])
	{
			
		Mainbranch M=new Mainbranch();//only the inherited class was instantiated and we now invoke the getDetails() and showDetails() method of the Headquarters class with the help of Super Keyword
		M.getDetails(); //When this method is called, first it will invoke the getDetails() method of Headquarters and then will progress to the Mainbranch class.
		M.showDetails();//Similary , first this method will show the details of Headquarters Class and then it will progress to the Mainbranch class.
	}
}

Sortie

Headquarters:
Enter City Where Headquarters is Sitiuated :
Delhi
Enter Total Number of Employees in Headquarters
1500
Main Branch:
Enter City Where Main Branch is Sitiuated
Indore
Enter The Total Number of Employees In Main Branch
500
Headquarters:
Company Headquarters is Sitiuated in Delhi and has 1500 Employees
Main Branch:
Company Main Branch is Sitiuated in Indore and has 500 Employees

REMARQUE : que dans le programme ci-dessus, nous utilisons deux variables de référence pour appeler le même nom de méthode :Super et M mais ce type de programme ne peut pas être considéré comme suivant le Polymorphisme.

Le polymorphisme est généralement appelé accès aux méthodes de classe enfant avec la référence de classe de base, nous discuterons de ce type de polymorphisme dans l'article à venir, ce type de polymorphisme est connu sous le nom de polymorphisme d'exécution et est réalisé à l'aide d'un mécanisme de programmation connu sous le nom de Dynamic Method Dispatch (DMD) .

Avant de plonger dans Dynamic Method Dispatch, veuillez lire l'utilisation du mot-clé abstrait dans la programmation Java via ce lien :Classes abstraites en Java avec exemple.

Publicité

Envisagez le programme pour DMD

import java.util.Scanner;

abstract class Shape
{
	Scanner KB=new Scanner(System.in);
	abstract void getDimensions();
	abstract void showArea();
}

class Reactangle extends Shape
{
	private double length, breadth,area;
	void getDimensions()
	{  	
		System.out.println("Enter Length of Rectangle");
		length=KB.nextDouble();
		System.out.println("Enter Breadth of Rectangle");
		breadth=KB.nextDouble();
	}

	void showArea()
	{
		System.out.println("Length of Reactangle:"+length);
		System.out.println("Breadth of Reactangle:"+breadth);
		System.out.println("Area of the Rectangle is:"+length*breadth);
	}
}

class Circle extends Shape
{
	private double radius,area;
	void getDimensions()
	{		
		System.out.println("Enter Radius of Circle");
		radius=KB.nextDouble();
	}
	void showArea()
	{		
		System.out.println("Radius of the Circle is:"+radius);
		System.out.println("Area of Circle :"+3.14*radius*radius);	
	}
}

class Triangle extends Shape
{
	private double baselength, height,area;
	void getDimensions()
	{
		System.out.println("Enter Base Length of Triangle");
		baselength=KB.nextDouble();
		System.out.println("Enter height of Triangle");
		height=KB.nextDouble();
	}

	void showArea()
	{
		System.out.println("Base Length of Triangle:"+baselength);
		System.out.println("Height of Triangle:"+height);
		System.out.println("Area of the Rectangle is:"+0.5*baselength*height);			
	}
	
	
}

class DMDShape
{
	public static void main(String args[])
	{
		Shape S;//will not be instantiated
		Reactangle R=new Reactangle();
		S=R;
		S.getDimensions();
		S.showArea();
		Circle C=new Circle();
		S=C;
		S.getDimensions();
		S.showArea();
		Triangle T=new Triangle();
		S=T;
		S.getDimensions();
		S.showArea();
		
	}	
}

Sortie

Enter Length of Rectangle
10
Enter Breadth of Rectangle
5
Length of Reactangle:10.0
Breadth of Reactangle:5.0
Area of the Rectangle is:50.0
Enter Radius of Circle
5
Radius of the Circle is:5.0
Area of Circle :78.5
Enter Base Length of Triangle
4
Enter height of Triangle
1
Base Length of Triangle:4.0
Height of Triangle:1.0
Area of the Rectangle is:2.0

Dans le programme ci-dessus, nous avons vu que les méthodes qui étaient définies dans la classe Shape étaient de type abstrait et que la classe Shape était héritée dans la classe Rectangle, Circle et Triangle, il est important de noter que les méthodes abstraites sont à redéfinir dans les classes dérivées et les méthodes abstraites ne doivent pas contenir de structures de corps dans la classe de base, donc dans la méthode principale, nous n'avons pas instancié l'objet Shape Class car c'est le point principal dont il faut se souvenir lors de l'utilisation de classes abstraites, avec l'aide de ci-dessus programme, nous avons pratiqué le concept de Run Time Polymorphism.


Balise Java