OOP polymorphism in simple words. Polymorphism - what is it? Genetic polymorphism

Polymorphism (programming)

Briefly, the meaning of polymorphism can be expressed by the phrase: "One interface, many implementations."

Polymorphism is one of four major mechanisms of object-oriented programming (along with abstraction, encapsulation and inheritance).

Polymorphism allows you to write more abstract programs and increase code reuse. General properties of objects are combined into a system that can be called differently - interface, class. The generality has an external and internal expression:

  • external generality manifests itself as the same set of methods with the same names and signatures (method names, argument types and their number);
  • internal commonality - the same functionality of methods. It can be described intuitively or expressed in the form of strict laws, rules that methods must obey. The ability to attribute different functionality to one method (function, operation) is called method overload (function overloading, overloading operations).

Examples

The class of geometric shapes (ellipse, polygon) can have methods for geometric transformations (shift, rotation, scaling).

In functional languages

There are two kinds of polymorphism in Haskell - parametric (pure) and ad hoc (class-based). Special call still ad hoc(from lat. ad hoc - specially). They can be distinguished as follows:

Parametric polymorphism

Special polymorphism

Haskell has a division into classes and instances (instance), which is not in OOP. A class defines a set and method signatures (perhaps giving some or all of them default implementations), and instances implement them. Thus, the problem of multiple inheritance automatically disappears. Classes do not inherit or override methods of other classes - each method belongs to only one class. This approach is simpler than the complex relationship of classes in OOP. A given data type may belong to more than one class; a class may require that each of its types necessarily belong to another class, or even several; the same claim may be made by an instance. This is analogous to multiple inheritance. There are also some properties that have no analogues in OOP. For example, the implementation of a list as an instance of the class of comparables requires that the elements of the list also belong to the class of comparables.

Programmers transitioning from OOP to FP should be aware of the important difference between their class system. If in OOP a class is “attached” to an object, i.e. to data, then in FP it is to a function. In FP, information about class membership is passed when the function is called, and is not stored in the fields of the object. This approach, in particular, allows solving the problem of the method of several objects (in OOP, the method is called on one object). Example: the addition method (numbers, strings) requires two arguments of the same type.

Implicit typing

Some programming languages ​​(for example, Python and Ruby) use the so-called duck typing (other names: latent, implicit), which is a kind of signature polymorphism. Thus, for example, in Python, polymorphism is not necessarily related to inheritance.

Forms of polymorphism

Static and dynamic polymorphism

(mentioned in the classic book by Sutter and Alexandrescu, which is the source).

Polymorphism can be understood as the presence of customization points in the code, when the same piece of code written by the programmer can mean different operations depending on something.

In one case, the particular meaning of a fragment depends on the environment in which the code was built. This is the so-called. static polymorphism. Function overloading, templates in C++ implement static polymorphism. If, for example, std::sort is called in the template class code, then the real meaning of the call depends on which type parameters this template will be expanded for - one of the std::sort will be called .

In another case, the specific meaning of the fragment is determined only at the execution stage and depends on how exactly and where it was built. given object. This is a normal, dynamic polymorphism, implemented through virtual methods.

Inclusion polymorphism

This polymorphism is called pure polymorphism. Using this form of polymorphism, related objects can be used generically. With substitution and inclusion polymorphism, you can write one method to work with all types of TPerson objects. Using inclusion and substitution polymorphism, you can work with any object that passes the "is-A" test. Inclusion polymorphism simplifies the work of adding new subtypes to the program, since you do not need to add a specific method for each new type, you can use an existing one only by changing the behavior of the system in it. With polymorphism, you can reuse a base class; use any descendant or methods that the base class uses.

Parametric polymorphism

Using Parametric polymorphism, you can create generic base types. In the case of parametric polymorphism, the function is implemented for all types in the same way, and thus the function is implemented for an arbitrary type. Parametric polymorphism deals with parametric methods and types.

Parametric methods

If inclusion polymorphism affects our perception of an object, then parametric polymorphism affects the methods used, since it is possible to create methods of related classes, deferring the declaration of types until runtime. To avoid writing a separate method of each type, parametric polymorphism is used, while the type of the parameters will be the same parameter as the operands.

Parametric types

Instead of writing a class for each specific type, we should create types that will be implemented at runtime, that is, we create a parametric type.

Override polymorphism

Abstract methods are often referred to as deferred methods. The class in which this method is defined can call the method, and polymorphism ensures that the appropriate version of the deferred method is called in child classes. Special polymorphism allows a special implementation for each type of data.

Polymorphism-overloading

This is a special case of polymorphism. Using overloading, the same name can denote different methods, and the methods can differ in the number and type of parameters, that is, they do not depend on their arguments. The method need not be limited to the specific types of parameters of many different types.

Comparison of polymorphism in functional and object-oriented programming

The class system in FP and in OOP are arranged differently, so their comparison should be approached very carefully.

Polymorphism is a rather isolated property of a programming language. For example, classes in C++ were originally implemented as a preprocessor for C. For Haskell, there is an algorithm for translating programs that use special polymorphism into programs with purely parametric polymorphism.

Despite the conceptual differences between class systems in FP and OOP, they are implemented in approximately the same way - using virtual method tables. It is often used in Java.

see also

Links

Notes


Wikimedia Foundation. 2010 .

See what "Polymorphism (programming)" is in other dictionaries:

    This term has other meanings, see Polymorphism. Polymorphism computer virus(Greek πολυ many + Greek μορφή form, appearance) a special technique used by the authors of malicious software ... ... Wikipedia

    In object-oriented programming, the ability of an object to choose the correct method based on the type of data received in a message. English: Polymorphism See also: Object oriented programming Financial dictionary ... ... Financial vocabulary

    Polymorphism (in programming languages) interchangeability of objects with the same interface. A programming language supports polymorphism if classes with the same specification can have a different implementation, for example, a class implementation ... ... Wikipedia

Polymorphism called the ability of a substance of the same composition to exist on the basis of external conditions in several crystalline forms (polymorphic modifications) with different structures (for simple substances, this phenomenon is sometimes called allotropy).

The phenomenon of polymorphism was first discovered by the German chemist and mineralogist E. Mitcherlich in 1821. Polymorphism is widespread in nature and is one of the characteristic properties of crystalline substances. Polymorphic modifications, differing in internal structure, have, in connection with this, different properties. Therefore, the study of polymorphism is extremely important for practice.

The external conditions that determine polymorphism primarily include temperature and pressure, therefore, each polymorphic modification has its own range of temperatures and pressures under which it exists in a thermodynamically stable (equilibrium) state and outside of which it cannot be stable, although it can exist in metastable, i.e. unbalanced state.

Carbon, silicon, phosphorus, iron and other elements exist in various polymorphic modifications. The physical properties of different modifications of the same substance can differ significantly. For example, carbon modifications that crystallize in the form of diamond (cubic system) or graphite (hexagonal system) differ sharply from each other in physical properties, despite the identity of the composition. If a polymorphic transformation is accompanied by minor changes in the structure, the physical properties of the substance change insignificantly. Each specific substance should have two, three or more polymorphic modifications. Various modifications are usually denoted by Greek letters. α, β, γ etc., and the first letters, as a rule, refer to modifications that are stable at higher temperatures.

When a high-temperature modification is converted into a lower-temperature one, the original external shape of the crystals is usually preserved, while internal structure substances undergo changes. This preservation of the external form, which does not correspond to the newly formed structure of the crystal lattice, is called paramorphosis. Paramorphoses are known in nature β -quartz (trigonal symmetry) by α -quartz (hexagonal symmetry), CaCO 3 calcite (trigonal symmetry) over aragonite (rhombic symmetry), etc.

Regardless of the nature of the structural changes that occur during polymorphic transformations, two types of them are distinguished: enantiotropic (reversible) and monotropic (irreversible) transformations.

Reversible transformation of one modification into another, carried out at a constant pressure and a certain transition temperature (point), at which these modifications are in a state of equilibrium, i.e. equally stable is called enantiotropic. Schematically, this can be represented as follows:

α ↔ β ↔ liquid

those. the transition α → β is enantiotropic. Examples of enantiotropic polymorphic transformations are transformations between polymorphic forms of SiO 2 ˸

Polymorphism - concept and types. Classification and features of the category "Polymorphism" 2015, 2017-2018.

  • - Polymorphism of individuals

    Human individuals, having a number of common properties, at the same time are not identical with each other in terms of species qualities. They differ from each other physically, mentally, and socially. Such differences are height, skin and hair color, appearance of the individual, gait, ... .


  • - Disruptive favors the preservation of extreme types and the elimination of intermediate ones. Leads to the preservation and strengthening of polymorphism.

  • - Intraspecific differentiation of mankind. Races as an expression of the genetic polymorphism of mankind. Species unity of mankind.

    INTRA-SPECIFIC DIFFERENTIATION OF HUMANITY: Since the emergence of H. sapiens, the social in man has become its essence and biological evolution has changed, manifesting itself in the emergence of a wide genetic polymorphism. Genetic diversity at the level ... .


  • classes are defined not by attribute sets, but by semantics. So, for example, the objects "stable" and "horse" can have the same attributes: price and age. At the same time, they can belong to the same class, if they are considered in the task simply as a product, or to different classes, if they are used differently within the framework of the task, i.e. different actions will be performed on them.

    Combining objects into classes allows us to consider the problem in a more general setting. A class has a name (e.g. "horse") that refers to all objects of that class. In addition, the class introduces the names of attributes that are defined for objects. In this sense, the declaration of a class is analogous to the declaration of a type of structure or record (record), which is widely used in procedural programming; at the same time, each object has the same meaning as an instance of a structure (a variable or constant of the corresponding type).

    Formally Class is a behavior pattern for objects of a certain type with given parameters that determine the state. All instances of the same class (objects derived from the same class) have the same set of properties and general behavior, that is, they react in the same way to the same messages.

    In accordance with UML(Unified Modeling Language - unified modeling language), the class has the following graphical representation .

    The class is depicted as a rectangle consisting of three parts. The name of the class is placed in the upper part, the properties of class objects are placed in the middle part, and the actions that can be performed with objects of this class (methods) are placed in the lower part.

    Each class can also have special methods that are automatically called when objects of that class are created and destroyed:

    • constructor(constructor) - executed when objects are created;
    • destructor( destructor ) - executed when objects are destroyed .

    Typically, a constructor and destructor have a special syntax, which may be different from the syntax used to write normal class methods.

    Encapsulation

    Encapsulation(encapsulation) is hiding the implementation of a class and separating its internal representation from the external (interface). When using an object-oriented approach, it is not customary to directly access the properties of a class from the methods of other classes. To access the properties of a class, it is customary to use special methods of this class to get and change its properties.

    Within an object, data and methods can have varying degrees of openness (or accessibility). The degrees of accessibility adopted in the Java language will be discussed in detail in Chapter 6. They allow more fine-grained control over the encapsulation property.

    The public members of a class make up the external interface of a . This is the functionality that is available to other classes. All properties of the class are usually declared private, as well as helper methods, which are implementation details and on which other parts of the system should not depend.

    By hiding the implementation behind the external interface of a class, you can change the internal logic of a particular class without changing the code of the rest of the system components. This property is called modularity.

    Ensuring that the properties of a class can only be accessed through its methods also has a number of advantages. Firstly, it is much easier to control the correct values ​​of the fields, because it is impossible to track the direct access to properties, which means that they can be assigned incorrect values.

    Secondly, it will not be difficult to change the way data is stored. If information becomes stored not in memory, but in long-term storage, such as file system or a database, only a few methods of one class would need to be changed, rather than introducing this functionality into all parts of the system.

    Finally, code written using this principle is easier to debug. In order to find out who and when changed the property of the object we are interested in, it is enough to add debug output to the method of the object, through which the property of this object is accessed. When using direct access to the properties of objects, the programmer would have to add debug output to all sections of the code where the object of interest to us is used.

    Inheritance

    Inheritance(inheritance) is a relationship between classes, in which a class uses the structure or behavior of another class (single inheritance), or other (multiple inheritance) classes. Inheritance introduces a public/private hierarchy in which subclass inherits from one or more more common superclasses. Subclasses usually supplement or redefine inherited structure and behavior.

    As an example, consider a task in which it is necessary to implement the classes "Car" and " Freight car". Obviously, these two classes have common functionality. So, they both have 4 wheels, an engine, can move, etc. Any car has all these properties, regardless of whether it is a truck or a car, 5- or 12-seater It is reasonable to move these common properties and functionality into a separate class, for example, "Car" and inherit the classes "Car" and "Truck" from it, in order to avoid re-writing the same code in different classes.


    The generalization relation is indicated by a solid line with a triangular arrow at the end. The arrow points to a more general class ( ancestor class or superclass ), and its absence to a more special class ( child class or subclass).

    The use of inheritance helps to reduce the amount of code created to describe similar entities, and also helps to write more efficient and flexible code.

    In this example, single inheritance is applied. A class can also inherit the properties and behavior of several classes at once. The most popular example of using multiple inheritance is designing an inventory system for a pet store.

    All animals in the pet store are descendants of the "Animal" class, as well as descendants of the "Product" class. Those. they all have age, need food and water, and at the same time have a price and can be sold.

    Multiple inheritance is depicted in the diagram in exactly the same way as single inheritance, except that the lines of inheritance connect the child class to several superclasses at once.

    Not all object-oriented programming languages ​​contain language constructs to describe multiple inheritance.

    In the Java language, multiple inheritance has limited support through interfaces and will be covered in Chapter 8.

    Polymorphism

    Polymorphism is one of the fundamental concepts in object-oriented programming along with inheritance and encapsulation. The word "polymorphism" is of Greek origin and means "having many forms". To understand what it means in relation to object-oriented programming Let's look at an example.

    Suppose we want to create a vector graphics editor in which we need to describe a set of graphic primitives in the form of classes - Point , Line , Circle , Box , etc. Each of these classes will define a draw method to display the corresponding primitive on the screen.

    Obviously, you will have to write code that, if necessary, to display a drawing, will sequentially iterate through all the primitives that are on the screen at the time of drawing, and call the draw method on each of them. A person not familiar with polymorphism will most likely create multiple arrays (a separate array for each type of primitive) and write code that iterates through the elements in each array and calls the draw method on each element. The result will be something like the following code:

    ... //create an empty array that can // contain Point objects with a maximum // size of 1000 Point p = new Point; Line l = new Line; Circle c = new Circle; Box b = new Box; ... // suppose this is where all arrays // are filled with corresponding // objects... for(int i = 0; i< p.length;i++) { //цикл с перебором всех ячеек массива. //вызов метода draw() в случае, // если ячейка не пустая. if(p[i]!=null) p[i].draw(); } for(int i = 0; i < l.length;i++) { if(l[i]!=null) l[i].draw(); } for(int i = 0; i < c.length;i++) { if(c[i]!=null) c[i].draw(); } for(int i = 0; i < b.length;i++) { if(b[i]!=null) b[i].draw(); } ...

    The disadvantage of the above code is the duplication of almost identical code for displaying each type of primitive. It is also inconvenient that with further modernization of our graphic editor and adding the ability to draw new types of graphic primitives, such as Text , Star , etc., with this approach, you will have to change the existing code and add new array definitions to it, as well as processing the elements contained in them.

    Using polymorphism, we can greatly simplify the implementation of such functionality. First of all, let's create a common parent

    Hello! This article is about one of the principles of OOP - polymorphism.

    What is polymorphism

    The definition of polymorphism sounds intimidating :)

    Polymorphism- this is the possibility of using methods of the same name with the same or different sets of parameters in one class or in a group of classes connected by an inheritance relationship.

    Word " polymorphism"may seem complicated - but it's not. You just need to break this definition into parts and show with examples what is meant. Believe me, at the end of the article, this definition of polymorphism will seem clear to you 🙂

    Polymorphism, if translated, it means "many forms". For example, an actor in a theater may take on many roles—or take on "many forms."

    So is our code - thanks to polymorphism, it becomes more flexible than in programming languages ​​that do not use the principles of OOP.

    So what forms are we talking about? Let's first give examples and show how polymorphism manifests itself in practice, and then return to its definition again.

    How polymorphism manifests itself

    The fact is that if Java did not have the principle of polymorphism, the compiler would interpret this as an error:

    As you can see, the methods in the picture differ in the values ​​they take:

    • first takes int
    • and the second takes String

    However, since Java uses the principle of polymorphism, the compiler will not treat this as an error, because such methods will be considered different:

    Naming methods the same way is very convenient. For example, if we have a method that looks for the square root of a number, it's much easier to remember a single name (for example, sqrt()) than one separate name for the same method written for each type:

    As you can see, we do not have to come up with a separate name for each method - and most importantly, remember them! Very comfortably.

    Now you can understand why this principle is often described with the phrase:

    One interface - many methods

    This assumes that we can fill in one name (one interface) on which we can call several methods.

    Method Overloading

    What we showed above - several methods with the same name and different parameters - is called overload. But it was an example of method overloading in one class. But there is one more case - overriding the methods of the parent class.

    Overriding Parent Methods

    When we inherit a class, we inherit all of its methods. But if we want to change any of the methods that we inherit, we can just override it. We are not obliged, for example, to create a separate method with a similar name for our needs, and the inherited method will be a "dead weight" in our class.

    It is the fact that we can create a class with the same name in the descendant class as the class that we inherited from the parent, and is called overriding.

    Example

    Let's imagine we have a structure like this:

    At the top of the class hierarchy is the class animal. It is inherited by three classes - cat, dog And Cow.

    The "Animal" class has a "voice" method. This method displays the message "Voice". Naturally, neither the dog nor the cat says "Voice" 🙂 They bark and meow. Accordingly, you need to set another method for classes cat, dog And Cow- so that the cat meows, the dog barks, and the cow says "Moo".

    Therefore, in the descendant classes, we override the method voice() so that we get "Meow", "Woof" and "Moo" in the console.

    • Please note: before the method that we are overriding, we write " @Override". This tells the compiler that we want to override the method.

    So what is polymorphism

    However, polymorphism is a principle. All the real examples that we have given above are only ways implementation of polymorphism.

    Let's look again at the definition we gave at the beginning of the article:

    Polymorphism- the possibility of using methods of the same name with the same or different sets of parameters in one class or in a group of classes connected by an inheritance relationship.

    Looks clearer, right? We have shown how you can:

    • create "methods of the same name" in the same class ("method overloading")
    • or change the behavior of parent class methods ("method overriding").

    All of these are manifestations of the "increased flexibility" of object-oriented languages ​​due to polymorphism.

    We hope our article was useful to you. Sign up for our Java courseswe have on .

    PHP, OOP, Encapsulation, Inheritance, Polymorphism

    In this lesson I will tell you about three basic concepts of Object Oriented Programming: Encapsulation, Inheritance, Polymorphism; And I will teach you how to apply them in development.

    Encapsulation

    Encapsulation - property programming language that allows you to combine and protect data and code into an object and hide implementation object from the user (programmer). At the same time, the user provided specification only ( interface) object.

    In other words, when working with a well-designed class, we can enjoy only by his methods, without delving into in how they are arranged and how they work with class fields. We are talking about a situation where we are working with a class developed by other programmers. We just use the already implemented functionality.

    Let's take another example. The principles of encapsulation as hiding the internal implementation are embedded in any PHP functions. You may already know the function strpos() to work with strings from the PHP standard library. This function searches a string for a given sequence of characters and returns its position as a number. If we think about the implementation of this function, we can assume that we will need to loop through each character from the beginning of the string for a match with the initial character of the desired sequence and, if so, compare the next two characters, etc. But we, as programmers no need to think over this and delve into the intricacies of the implementation of this function. We've had enough know the parameters, which it accepts, and the format return value. The strpos() function encapsulates the solution to the substring search problem, offering us only an external interface for using it.

    Similarly, well-designed classes hide their internal implementation by providing an interface to external users in the form of a set of methods.

    IN PHP language the concept of encapsulation is implemented in the form of special access modifiers to fields and methods of classes. We will talk about this further.

    Inheritance

    Inheritance - an object-oriented programming mechanism that allows you to describe a new class based on the existing(parent), while the properties and functionality of the parent class are borrowed by the new class.

    Let's take an example of inheritance from real life. As a class, you can take a geometric figure. However, we do not specify what specific figure should be. What properties of the figure can be distinguished? Suppose it has color. Then in the class describing the shape, there must be a corresponding field of string type that specifies the color of the shape. Also, any geometric figure has an area. Let area be the second property of our class.

    Now suppose that our program needs to work with specific geometric shapes: squares And triangles, including their geometric position on the plane. Obviously, the description of triangles and squares using the class Figure will be insufficient because it does not store information about the geometric position. Therefore, we need to introduce two more classes: Square And Triangle. In this case, let's assume that in our program we also need the colors and areas of the figures. This situation just requires the use of inheritance. Because any square and triangle in the program is obviously a figure, that is, it has a color and an area. At the same time, each figure requires additional data (besides color and area) for its description, which is solved by introducing two additional classes for squares And triangles, which are inherited from the class Figure.

    This means that in the classes Square And Triangle we don't have to re-set the color and area fields. It suffices to indicate that the mentioned classes are inherited from the Shape class.

    Now let's look at another example that is closer to the realities of web programmers. Nowadays blogs have become very popular on the Internet. In fact, a blog is just a collection of articles. And the key entity in the development of the blog is the article.

    Now let's imagine that in our future blog, articles can have Various types. To begin with, let's focus on two types: a regular note article and a news article. For a news article, the date of its publication is important, because it carries some specific news.

    To implement this situation in PHP, we need to define two classes: a class for a regular note article and a class for a news article. At the same time, let the news article expand the capabilities of a regular article, i.e. inherited from her. For class inheritance in PHP, use keyword extends.

    Class ( ... // class content ) class ( ... // class content )

    The above code defines a class NewsArticle as heir article. Class article in turn is the parent of the class NewsArticle. This means that the fields and methods of the class article will also be present in the class NewsArticle, and there is no need to redefine them.

    With the help of inheritance, you can build a whole hierarchy of classes, inheriting one from the other. At the same time, any class can have only one parent:


    Sometimes we may need redefine one of the methods of the parent class. Let's revisit the implementation of the class article:

    Class Article ( ... // class fields // Function for displaying the article function view() ( echo "

    $this->title

    $this->content

    "; } }

    Let's assume that the output of a news article should be different from the presentation of a regular article, and we should additionally display the time the news was published. However, in the class article method already exists view() The responsible for displaying the article. You can do it in two ways. In the first case, you can come up with a new method in the class NewsArticle, for example, with the name viewNews() especially for news release. However, it is more correct to use the same methods to perform similar actions in inherited classes. Therefore, it would be better if the method for displaying news in the class NewsArticle will be named the same as in the parent class - view(). To implement such logic in PHP, it is possible to override parent methods, i.e., set methods in child classes with names that match in parent classes. The implementation of these methods in parent classes in this case becomes irrelevant for the descendant class. Let's take an example class NewsArticle with overridden method view():

    Class NewsArticle extends Article ( $datetime; // date of publication of the news // Function for displaying the article function view() ( echo "

    $this->title

    ".strftime("%d.%m.%y", $this->datetime)." News

    $this->content

    "; } }

    The above code uses the function strftime(), which allows you to display dates in a convenient form. For a better understanding of the code, read the specification for this function in the reference. For us, it is now important that you pay attention to the fact that the class NewsArticle, like article, defines the method view(). Accordingly, all objects of this class will use the method view(), declared in the class NewsArticle, not in article.

    You may be wondering: why is it still important to override some methods instead of introducing new methods in descendant classes? Understanding this will come along with understanding the next most important concept of OOP.

    Polymorphism

    Polymorphism - interchangeability of objects with the same interface.

    A programming language supports polymorphism if classes with the same specification can have different implementations - for example, a class's implementation can be changed through inheritance. This is exactly what we saw in the previous articles example.

    Let's look at the following example which gives understanding of the essence of polymorphism:

    Class A ( function Test() ( echo "This is class A
    "; ) function Call() ( $this->Test(); ) ) class B extends A ( function Test() ( echo "This is class B
    "; ) ) $a = new A(); $b = new B(); $a->Call(); // prints: "This is class A" $b->Test(); // prints: " This is class B" $b->

    Notice the comments on the last three lines. Try it on your own explain this result.. It is advisable to implement and test this example yourself. Take the time to fully understand how the script works, because this little example has a deep meaning of OOP. Now let's try to parse the proposed code together.

    $a->Call(); // prints: "This is class A"

    This line calls the method Call() on a class object A. As defined in the function Call() class A, the method is called Test(). Works out the method Test() on a class object A, and the text "This is class A" is displayed.

    $b->Test(); // prints: "This is class B"

    This line calls the method Test() on a class object B. Method Test() class B displays the text "This is class B".

    $b->Call(); // prints: "This is class B"

    Finally, on the last line, the class is called Call() on a class object IN. But in the class implementation B we will not see such a method, which means that it is inherited from the class A, since the class B is a child of the class A. What do we see in the implementation of the method Call() class A? Following code:

    $this->Test();

    Method Call() calls a method Test() the object in which it is located. This means that the method will work Test() class object B. This explains the result displayed on the screen.

    This is what principle of polymorphism. Classes can have same methods, but their implementation is different. When developing script code, we can only know the specification of their methods common to a group of classes, but not have an idea of ​​which particular class instance will be used at a particular point in time.

    The concepts of encapsulation, inheritance and polymorphism can be called three whales OOP. Understanding and competent application of the principles of these concepts - recipe for success development using OOP.

    Computer