다형성의 이점
다형성의 이점을 찾기 시작했을 때 여기 에서이 질문을 발견했습니다 . 그러나 여기서 나는 내 대답을 찾을 수 없었습니다. 내가 찾고 싶은 것을 말하겠습니다. 여기에 몇 가지 수업이 있습니다.
class CoolingMachines{
public void startMachine(){
//No implementationion
}
public void stopMachine(){
//No implementationion
}
}
class Refrigerator extends CoolingMachines{
public void startMachine(){
System.out.println("Refrigerator Starts");
}
public void stopMachine(){
System.out.println("Refrigerator Stop");
}
public void trip(){
System.out.println("Refrigerator Trip");
}
}
class AirConditioner extends CoolingMachines{
public void startMachine(){
System.out.println("AC Starts");
}
public void stopMachine(){
System.out.println("AC Stop");
}
}
public class PolymorphismDemo {
CoolingMachines cm = new Refrigerator();
Refrigerator rf = new Refrigerator();
}
이제 여기에서 Demo 클래스에 두 개의 개체를 만들고 Refrigerator
. rf
객체 에서의 trip()
메서드 를 호출 할 수 Refrigerator
있지만 해당 메서드가 cm
객체에 대해 숨겨진 다는 것을 완전히 이해했습니다 . 이제 내 질문은 왜 다형성을 사용해야합니까?
CoolingMachines cm = new Refrigerator();
내가 괜찮을 때
Refrigerator rf = new Refrigerator();
다 형체의 효율이 좋은가요 아니면 가벼운가요? 이 두 개체의 기본 목적과 차이점은 무엇입니까? 사이에 어떤 차이가 있나요 cm.start();
과 rf.start()
?
목록을 처리 할 때 유용합니다 ... 간단한 예 :
List<CoolingMachines> coolingMachines = ... // a list of CoolingMachines
for (CoolingMachine current : coolingMachines) {
current.start();
}
또는 메서드가 하위 클래스와 함께 작동하도록 허용하려는 경우 CoolingMachines
구체적인 클래스를 아는 것이 정말 괜찮은 경우에는 이점이 없습니다. 그러나 대부분의 경우 기본 클래스 또는 인터페이스에 대해서만 알고있는 코드를 작성할 수 있기를 원합니다.
예를 들어, 봐 Iterables
에서 구아바 - (주로) 어떤 구현 상관 없어 방법이 많이있어 그 Iterable
사용됩니다. 모든 구현에 대해 모든 코드를 별도로 원하십니까?
추상 기본 클래스 또는 인터페이스로 코딩 할 수 있는 경우 나중에 동일한 공용 API를 공유하지만 다른 구현을 가질 수있는 다른 구현을 사용할 수 있습니다. 단일 프로덕션 구현 만 원하더라도 테스트를위한 대체 구현이 필요할 수 있습니다. (이가 적용되는 정도는 해당 클래스에 따라 다릅니다.)
나중에 냉각 AirConditioner
대신 사용하려는 경우 Refrigerator
변경해야하는 코드 만CoolingMachines cm = new AirConditioner();
사용하고 싶은 이유
CoolingMachines cm = new Refrigerator();
나중에 쉽게 다른 CoolingMachines
. You only need to change that one line of code and the rest of the code will still work (as it will only use methods of CoolingMachines
, which is more general than a specific machine, such as a Refrigerator
).
따라서의 특정 인스턴스에 대해 동일한 방식으로 Refrigerator
호출 cm.start();
하고 rf.start()
작동하지만 cm
다른 CoolingMachines
객체 가 될 수도 있습니다 . 그리고 그 객체는 다른 구현을 가질 수 있습니다.start()
.
First answer:
메서드 재정의 및 메서드 오버로딩에 다형성을 사용합니다. 다른 클래스에서 사용되는 다른 클래스 메서드는 두 가지 옵션이 있습니다. 첫 번째 메서드는 상속되고 두 번째 메서드는 덮어 쓰기됩니다. 여기에 인터페이스 확장 : 그것들을 사용하거나 구현 방법 : 로직을 작성합니다. 메서드, 클래스 상속에 사용되는 다형성.
두 번째 대답 :
cm.start();
와 사이에 차이가 있습니까?rf.start();
?
Yes, both are objects that are completely different with respect to each other. Do not create interface objects because Java doesn`t support interface objects. First object created for interface and second for Refrigerator class. Second object right now.
The most general answer to the general part of your question (why should I use polymorphism?) is that polymorphism realizes a few critical object-oriented design principles, for example:
code reuse: By putting any code that is common to all of your 'cooling-machines' into cooling-machine, you only need to write that code once and any edits to that code trickle down instantly.
abstraction: Human brains can only keep track of so much stuff, but they are good at categories and hierarchies. This helps understand what's happening in a big program.
encapsulation: each class hides the details of what it's doing and just builds on the interface of the base class.
separation of concerns: a lot of object oriented programming is about assigning responsibilities. Who is going to be in charge of that? Specialized concerns can go in subclasses.
So polymorphism is just part of the bigger oo picture, and the reasons for using it sometimes only make sense if you are going to try and do 'real' oo programming.
A simple use case of polymorphism is that you can have an array of coolingMachines where element 0 is a refrigator and element 1 is an AirConditioner etc...
You do not need to preform any checks or make sure which object you are dealing with in order to call trip or start etc.
This can be a great benefit when taking input from a user and having to iterate over all the objects and call similar functions
I'll give an easy to understand example. Lets say you have some json
{"a":[1,2],"sz":"text", "v":3, "f":1.2}
Now lets say programmatically you want to list the name, type and value. Instead of having a switch() for each type (array for a, string for sz, etc) you can just have a base type and call a function which does its job. It is also more cpu efficient than using a switch with a dozen types.
Then there are plugins, libs and foreign code with interface reasons.
Using your objects polymorphically also helps to create factories or families of related classes which is an important part of how Factory Design Pattern is implemented. Here's a very basic example of polymorphic factory:
public CoolingMachine CreateCoolingMachines(string machineType)
{
if(machineType == "ref")
return new Refrigerator();
//other else ifs to return other types of CoolingMachine family
}
usage of calling above code:
CoolingMachine cm = CreateCoolingMachine("AC"); //the cm variable will have a reference to Airconditioner class which is returned by CreateCoolingMachines() method polymorphically
Also, imagine that you have a method as below that uses concrete class parameter Refrigerator
:
public void UseObject(Refrigerator refObject)
{
//Implementation to use Refrigerator object only
}
Now, if you change above implementation of UseObject()
method to use most generic base class parameter, the calling code would get advantage to pass any parameter polymorphically which can then be utilized inside the method UseObject()
:
public void UseObject(CoolingMachine coolingMachineObject)
{
//Implementation to use Generic object and all derived objects
}
Above code is now more extensible as other subclasses could be added later to the family of CoolingMachines, and objects of those new subclasses would also work with the existing code.
참고URL : https://stackoverflow.com/questions/11082640/benefit-of-polymorphism
'developer tip' 카테고리의 다른 글
업데이트 패널 포스트 백 후 JavaScript 콜백을 실행하는 방법은 무엇입니까? (0) | 2020.10.31 |
---|---|
행렬에서 주어진 값의 요소 수를 어떻게 계산할 수 있습니까? (0) | 2020.10.31 |
내 정렬 루프가하지 말아야 할 요소를 추가하는 것처럼 보이는 이유는 무엇입니까? (0) | 2020.10.31 |
OnItemClickListener android를 사용한 ListView (0) | 2020.10.31 |
HttpClient 4.0.1-연결 해제 방법? (0) | 2020.10.31 |