다형성-단 두 문장으로 정의
다른 정의와 설명을 살펴 보았지만 만족스러운 것은 없습니다. 누구나 코드 나 예제를 사용하지 않고 최대 두 문장으로 다형성을 정의 할 수 있는지 확인하고 싶습니다. 나는 '그래서 당신은 사람 / 자동차 / 캔 오프너를 가지고 있습니다 ...'또는 그 단어가 어떻게 파생되는지 듣고 싶지 않습니다 (폴리와 모프가 무엇을 의미하는지 아는 사람은 아무도 없습니다). 다형성이 무엇인지 아주 잘 이해하고 영어를 잘 구사할 수 있다면이 질문에 조밀하지만 짧은 정의로 대답 할 수 있어야합니다. 당신의 정의가 다형성을 정확하게 정의하지만 너무 조밀해서 몇 번의 읽기가 필요하다면, 그것이 바로 제가 찾고있는 것입니다.
왜 두 문장 만? 정의는 짧고 지능적이기 때문입니다. 설명은 길고 예제와 코드가 포함되어 있습니다. 여기에서 설명을 찾으십시오 (해당 페이지의 답변이 제 질문에 만족스럽지 않습니다).
다형성 대 재정의 대 오버로딩
가능한 한 쉽게 다형성을 설명하십시오.
이 질문을하는 이유는 무엇입니까? 같은 질문을 받았고 만족스러운 정의를 내놓을 수 없다는 것을 알게 되었기 때문입니다 (제 기준으로는 꽤 높음). 나는이 사이트의 위대한 사람들이 그것을 할 수 있는지보고 싶다.
두 문장 요구 사항을 정말로 만들 수 없다면 (정의하기 어려운 주제) 넘어가도 괜찮습니다. 아이디어는 실제로 다형성이 무엇인지 정의하고 그것이 무엇을하는지 또는 어떻게 사용하는지 설명하지 않는 정의를 갖는 것입니다 (차이를 얻었습니까?).
다형성은 일종의 계약의 표현을 허용하며 잠재적으로 많은 유형이 해당 계약을 (클래스 상속을 통해 여부에 관계없이) 각각의 목적에 따라 다른 방식으로 구현합니다. 해당 계약을 사용 하는 코드 는 어떤 구현이 관련되어 있는지 (*) 신경 쓸 필요가 없으며 계약이 준수 될 것입니다.
(*) 어쨌든 이상적인 경우-분명히 꽤 자주 호출 코드가 매우 신중하게 적절한 구현을 선택했습니다!
일반적으로 과일을 먹을 수는 있지만 과일의 종류는 다양합니다. 과일 인 사과는 먹을 수 있습니다 (과일이기 때문에). 바나나도 먹을 수 있지만 (과일이기도하므로) 사과와는 다른 방식입니다. 먼저 껍질을 벗기세요.
글쎄, 적어도 나는 그렇습니다. 그러나 나는 어떤 매너에서 이상해서 무엇을 압니까?
이것은 상속 (과일을 먹을 수 있음), 다형성 (과일을 먹는 것이 모든 종류의 과일을 먹을 수 있음) 및 캡슐화 (바나나에 껍질이 있음)를 보여줍니다.
진지하게, 객체 상속, 다형성, 캡슐화, 가상의 것, 추상적 인 것, 사적인 것, 공개적인 것, 이것들은 모두 어려운 개념입니다. 누군가가 이것에 대한 2 문장 정의를 절대적으로 갖고 싶다면 질문에 코드 골프 변형으로 태그를 지정하십시오. 그러한 두 문장은 너무 간결해야하므로 이미 무엇인지 알지 못하면 충분히 배울 수 없습니다. 더 자세히 알아야 할 사항을 알 수 있습니다.
다형성은 유형을 인식하지 않는 균일 한 인터페이스를 선언하여 구현 세부 사항을 인터페이스를 구현하는 구체적인 유형에 남겨 둡니다.
사실, 여러 형태의 다형성이 있고 그것에 대해 꽤 많은 논란이 있습니다. 그것을 제대로 정의 할 수없는 CS 교수를 볼 수도 있습니다. 나는 세 가지 유형을 알고 있습니다.
임시 다형성 (오리처럼 보이고 오리처럼 걷는다 => 오리입니다). 예를 들어 Haskell과 Python에서 볼 수 있습니다.
일반 다형성 (여기서 유형은 일반 유형의 인스턴스입니다). 예를 들어 C ++에서 볼 수 있습니다 (int의 벡터와 문자열의 벡터는 모두 멤버 함수 크기를 가짐).
하위 유형 다형성 (유형이 다른 유형에서 상속되는 경우). 대부분의 OO 프로그래밍 언어에서 볼 수 있습니다 (즉, 삼각형은 모양입니다).
Wikipedia : Polymorphism은 균일 한 인터페이스를 사용하여 다양한 데이터 유형의 값을 처리 할 수있는 프로그래밍 언어 기능입니다. 저에게는 매우 간단합니다.
이 질문을하는 이유를 정말 이해합니다. 나는 다형성을 이해하지만 면접에서 다형성에 대한 짧고 명확한 정의를 제공하라는 요청을 받았습니다. 명확하고 짧은 정의를 할 수 없었기 때문에 그것에 대해 생각하기 시작했고 여기에 내 정의가 있습니다.
한 유형의 객체가 하나의 동일한 인터페이스를 갖지만이 인터페이스의 다른 구현을 갖는 기능.
정의 :
다형성은 $ 1 아이디어에 대한 $ 10 단어입니다. 즉, 수행 할 작업을 요청할 때 최종 결과가 적절한 한 그것이 어떻게 달성되는지는 신경 쓰지 않습니다. 긴만큼 서비스가 제대로 제공되고, 난 상관 없어 [정보 구현 .
토론
소프트웨어 개발, 특히 객체 지향 원칙에 따라 개발 된 시스템에서 일반적으로 사용되지만 다형성은 기본적으로 실제 원칙이며 기술 용어가 아닌 실제 용어로 정의되어야합니다.
예
전화를 걸고 싶을 때 전화를 들고 전화를 걸어 상대방과 통화를합니다. 나는 전화를 누가 만들 었는지, 어떤 기술을 사용하는지, 유선, 무선, 모바일 또는 VOIP인지, 보증 대상인지는 상관하지 않습니다.
문서를 인쇄하고 싶을 때 인쇄합니다. 구현 언어, 프린터 브랜드, 연결 스타일, 소모품 또는 용지의 품질에 대해서는 신경 쓰지 않습니다.
동일한 인터페이스의 여러 구현.
예 : 많은 전화기 모델이 숫자 키패드 인터페이스를 구현합니다.
다형성은 코드를 단순화하기 위해 객체 모델을 디자인 할 때 사용되는 객체 지향 전략입니다. 핵심 다형성은 두 개의 유사하지만 다른 객체를 정의한 다음 두 객체를 동일한 것처럼 취급하는 기능입니다.
알겠습니다 ....
다형성이 무엇인지에 대한 나만의 해석을 추가 할 것이라고 생각했습니다. 매우 일반적으로 다형성은 서로 다른 유형의 엔티티에 단일 인터페이스 를 제공하는 행위입니다 .
그것은 다소 일반적이지만 내가 아는 세 가지 유형의 다형성 ( ad hoc , parametric 및 subtype)을 모두 래핑 할 수있는 유일한 방법 입니다. 아래에서 더 자세히 살펴보고 다형성 유형을 이름별로 알파벳순으로 정렬했습니다. 당신이 관심을 가지고있는 것은 아마도 마지막 것 인 subtype polymorphism 일 것입니다.
임시 다형성
임시 다형성 은 다른 매개 변수 유형에 대해 동일한 메소드의 여러 구현을 제공하는 행위입니다. 에서 OOP , 일반적으로 알려진 방법 오버로딩 . 예를 들면 :
public String format(int a) {
return String.format("%2d", a);
}
public String format(Date a) {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(a);
}
Both format
methods share a single interface, but they work on entities of different types.
Parametric polymorphism
Parametric polymorphism is the act of making a class (or method) work on a type that is itself a parameter of the class (or method). It's often referred to as generics.
For example, Java's List[T]
expects a parameter T
at instantiation time, and this parameter defines the type of the resulting object.
Note for purists that I'm purposefully ignoring raw types as I feel they'd just muddy the waters in this context.
List[String]
and List[Date]
share a single interface, but work on (and are) different types.
Subtype polymorphism
Subtype polymorphism is probably what you initially meant in your question: It's the act of providing a single interface to multiple implementations of the same type.
To use the customary example: Animal
provides a contract that all implementations must respect. Dog
is an Animal
, and as such supports all operations that Animal
declares. According to the Liskov substitution principle, this allows you to use an instance of Dog
where an instance of Animal
is expected (but not the other way around).
If Cat
and Dog
are both subclasses of Animal
, then they share a single interface but are in fact different types.
I'm going off in a bit of a tangent here, but subtype polymorphism is (I think) the only one that allows overriding: the act of redefining the behaviour of a method defined by a parent class. This is often confused with overloading which, as we saw before, is a type of polymorphism and doesn't in fact need subclassing (nor does it need classes, really).
Polymorphism is a software coding abstraction where several different underlying entities (usually data, but nit always) all share a common interface which allows them to look and act identical at runtime. We use this as a development technique to enforce consistent behavior over a wide range of similar, but not identical instances with an absolute minimal implementation, thus reducing the expectation for bugs and inconsistencies.
Paul.
polymorphism == multiple classes + same method signatures + class-specific behavior.
It seems that the best definitions are provided here, so let me add my two cents please, just for other observers. I hope it could help more.
There are two kinds of polymorphism:
1. Compile-time (static) polymorphism or (ad hoc) polymorphism.
That is simply method overloading and operator overloading
2. Run time or (dynamic) polymorphism.
The first term is inherited from the Java and C++ terminology.
But in the .NET terminology only the second one (I mean run time polymorphism) is really supposed as polymorphism and simply called polymorphism.
And as far as I know there are three methods for implementing (run time) polymorphism.
1. Parametric polymorphism or simply the use of generics (templates in C++).
2. Inheritance-based polymorphism or subtyping.
3. Interface-based polymorphism.
A simple example Of interface-based polymorphism:
interface Imobile
{
void Move();
}
class Person :Imobile
{
public void Move() { Console.WriteLine("I am a person and am moving in my way."); }
}
class Bird :Imobile
{
public void Move() { Console.WriteLine("I am a bird and am moving in my way."); }
}
class Car :Imobile
{
public void Move() { Console.WriteLine("I am a car and am moving in my way."); }
}
class Program
{
static void Main(string[] args)
{
// Preparing a list of objects
List<Imobile> mobileList = new List<Imobile>();
mobileList.Add(new Person());
mobileList.Add(new Bird());
mobileList.Add(new Car());
foreach (Imobile mobile in mobileList)
{
mobile.Move();
}
// Keep the console open
Console.WriteLine("Press any key to exit the program:");
Console.ReadKey();
}
}
Output:
I am a person and am moving in my way.
I am a bird and am moving in my way.
I am a car and am moving in my way.
Press any key to exit the program:
Multiple forms of a single object is called Polymorphism.
Polymorphism is ability of an object to appear and behave differently for the same invocation. ex: each animal appear and sound differently ( when you hit it :) )
Polymorphism is a feature of programming languages that allows an object to be treated as an instance of its supertype.
Giving a single name to a set of analogous operations on different types. When done well, the analogy is obvious e.g. "adding" numbers arithmetically and "adding" strings by concatenation (which sums their lengths).
Polymorphism
Different objects can respond to the same message in different ways, enable objects to interact with one another without knowing their exact type.
Via: http://www.agiledata.org/essays/objectOrientation101.html
This is the definition that I've always followed:
Two objects are polymorphic (with respect to a particular protocol) between them, if both respond to the same messages with the same semantic.
Polymorphism is about messages, is about being able to respond the same set of messages with the same semantic.
If two object CAN respond to empty? but the semantic of the message is different, then.. they are not polymorphic.
Polymorphism at the lower level is the ability to invoke methods that are defined by the implementors of an interface from the interface instance.
Polymorphism is a programming feature that allows an object to have many types ('shapes') and lets you treat it as any of those types depending on what you need to do without knowing or caring about its other types.
Polymorphism is language functionality allowing high-level algorithmic code to operate unchanged on multiple types of data. And the other sentence, whatever it was for... ;-P.
( The types C++ supports are listed and contrasted in my answer: Polymorphism in c++ )
Polymorphism concept became a phenomenon lately. Here is the actual drift. Runtime defines which submethod should be invoked by a reference of a super class. Now, what does mean in practice? It means actually nothing. You can code simply without polymorphism. So, why? Because, if we haven't got the polymorphism, we had to memorize all the subclass functions definitions. Polymorphism saves us from this in practice.
You can define a list as follows:
List list = new List();
but if you check for IList
, you can benefit of the interface as:
IList list = new List();
and use the IList
reference freely. Assuming IList
is also implemented in another class, you can use methods of that unknown class via again IList
reference without trying to remember that class name. Marvelous, isn't it?
Now, more valuable information is coming:
Java is by default polymorphic, whereas .NET and C++ are not, in MS, you have to declare the base function virtual
(and in .NET override
keyword).
Also, there are 2 integral rules in polymorphism. One is inheritance (via interface impl. or via class extending) and the other is overriding. Without overriding, polymorphism doesn't exist. Note that method overloading (which always in a single class) is also a type of "minimalistic" polymorphism.
For a given method signature, different method implementations are run for different, hierarchically related, classes.
Polymorphism is the ability of using different classes that implement a common interface (or extend a common base class) in a common way, without needing to now the specific implementation, and using only the methods available in the common interface.
Ie: In Java, as ArrayList and LinkedList both implement List, if you declare a variable as List, you can always perform the operations allowed in List, no matter which if you variable was instanced as an ArrayList or a LinkedList.
Entities of the same type (that is, implemented same interface or derived from same class), behave in different ways (under same method name).
I think implementation of methods of the same signature in different classes (having some sort of inheritance relation either using extends or implements) is method overriding and also polymorphism because in this way we are achieving many forms of the same method signature.
I guess sometimes objects are dynamically called. You are not sure whether the object would be a triangle, square etc in a classic shape poly. example.
So, to leave all such things behind, we just call the function of derived class and assume the one of the dynamic class will be called.
You wouldn't care if its a sqaure, triangle or rectangle. You just care about the area. Hence the getArea method will be called depending upon the dynamic object passed.
Polymorphism is the ability of a function to automatically adapt to accept input data of different data types. You can 'Add' two doubles '1.1' and '2.2' and get '3.3' or 'Add' two strings "Stack" and "Overflow" and get "StackOverflow".
Polymorphism is when different objects respond to the same method in a different way. For example, a car moves on the road while a person walks on the road. Those are two objects responding to the same road in a different way.
참고URL : https://stackoverflow.com/questions/409969/polymorphism-define-in-just-two-sentences
'programing tip' 카테고리의 다른 글
C #에서 선행 문없이 {} 코드 블록을 허용하는 이유는 무엇입니까? (0) | 2020.09.20 |
---|---|
부트 스트랩 3에서 'x'가있는 검색 상자를 지우려면 어떻게합니까? (0) | 2020.09.20 |
컴파일 시간에 "SimDeviceType 유형에 적합한 장치를 찾지 못함"문제와 함께 iOS 빌드 실패 (0) | 2020.09.20 |
PHP를 사용하여 원격 파일이 존재하는지 어떻게 확인할 수 있습니까? (0) | 2020.09.20 |
iPhone의 온 스크린 키보드 높이는 얼마입니까? (0) | 2020.09.20 |