Thinking Logic of computer program (15)-Initial knowledge inheritance and polymorphism

Source: Internet
Author: User
Tags getcolor gety

Inherited

In the previous section, we talked about mapping the concept of reality into the concept of a program, we talked about the combination of classes and classes, there is a very important relationship between the concepts in reality, that is, classification , there is a root, and then continue to refine downward, forming a hierarchical classification system. This example is very numerous:

In the natural world, animals and plants, animals have different subjects, carnivores, herbivores, omnivorous animals, predators have wolves, dogs, tigers, etc., these are divided into different varieties ...

Open e-commerce website, in a prominent position generally have a list of categories, such as household appliances, clothing, clothing has women's, men's, men's shirts, jeans, etc...

Computer programs often use inheritance relationships between classes to represent the classification relationships between objects. In the inheritance relationship, there are parents and subclasses , such as the animal class animal and the dog class Dog,animal are the parent class, and dog is the subclass. The parent class is also called the base class , the subclass is also called the derived class , the parent subclass is relative, and a class B may be a subclass of Class A, which is the parent class of Class C.

Inheritance is called because the subclass inherits the properties and behavior of the parent class, the parent class has properties and behaviors, and the subclass has. However, subclasses can increase the properties and behaviors that are unique to subclasses, and some parent classes have behaviors that may not be implemented in exactly the same way as the parent class.

The use of inheritance on the one hand can be reused code, the public properties and behavior can be put into the parent class, and the subclass only need to focus on the subclass of the unique can, on the other hand, the different subclasses of the object can be more convenient to be unified processing.

This section introduces the inheritance in Java through some simple examples of graphics processing, introduces the basic concepts of inheritance, the more in-depth discussion of inheritance, and the principle of implementation, which we introduce in subsequent chapters.

Object

In Java, all classes have a parent class, even if the parent class is not declared, and there is an implicit parent class called Object. Object does not have a property defined, but some methods are defined, as shown in:


We'll introduce the ToString () method in this section, and we'll walk through the other steps in the next section. The purpose of the ToString () method is to return the text description of an object, which can be used directly by all classes.

For example, for the point class we introduced earlier, you can use the ToString method:

New Point (2,3); System.out.println (P.tostring ());

The output looks like this:

[Email protected]

What does that mean? Before @ is the class name, what is the content after @? Let's look at the ToString code:

 Public String toString () {    return getclass (). GetName () + "@" + integer.tohexstring (Hashcode ());}

GetClass (). GetName () returns the class name of the current object, Hashcode () returns the hash value of an object, which we will describe in subsequent chapters, which can be understood as an integer, which, by default, is usually the memory address value of the object. Integer.tohexstring (Hashcode ()) returns the 16 binary representation of this hash value.

Why do you write this? Writing a class name is understandable, representing the type of the object, and writing the hash is a last resort, because the object class does not know the properties of the specific object, does not know how to describe it, but needs to distinguish between different objects, only to write a hash value.

But subclasses are aware of their own properties, and subclasses can override the methods of the parent class to reflect their different implementations. the so-called rewrite is to define the same method as the parent class and re-implement it.

Point class-Overriding ToString ()

Let's look at the point class again, and this time we rewrote the ToString () method.

 Public classPoint {Private intx; Private inty;  PublicPoint (intXinty) { This. x =x;  This. y =y; }     Public Doubledistance (point point) {returnMath.sqrt (Math.pow ( This. X-point.getx (), 2)                +math.pow ( This. Y-point.gety (), 2)); }         Public intGetX () {returnx; }         Public intGetY () {returny; } @Override PublicString toString () {return"(" +x+ "," +y+ ")"; }}

The ToString method is preceded by a @Override, which means that the method of ToString is the overridden method of the parent class, and the overridden method returns the value of the x and Y coordinates of the point. When overridden, the implementation of the subclass is called. For example, the output of the following code becomes: (2,3)

New Point (2,3); System.out.println (P.tostring ());

Graphics processing Classes

Next, let's take a look at the image in a few examples of graphical processing:

These are some basic graphics, graphics wired, squares, triangles, circles and so on, graphics have different colors. Next, we define the following classes to illustrate some of the concepts of inheritance:

    • The parent class shape, which represents the graphic.
    • Class Circle, which represents the circle.
    • Class line, which represents the straight lines.
    • Class Arrowline that represents a straight line with arrows.

Graphics (SHAPE)

All graphs have a property that represents a color, there is a method for drawing, and the following is the code:

 Public classShape {Private Static FinalString Default_color = "BLACK"; PrivateString color;  PublicShape () { This(Default_color); }     PublicShape (String color) { This. color =color; }         PublicString GetColor () {returncolor; }     Public voidsetcolor (String color) { This. color =color; }         Public voidDraw () {System.out.println ("Draw Shape"); }}

The above code is basically nothing to explain, the instance variable color represents the color, the Draw method represents the drawing, we do not write the actual drawing code, mainly to demonstrate the inheritance relationship.

Circle (Circle)

The circle inherits from shape, but includes additional properties, center points and radii, as well as an additional method area for calculating areas, in addition to overriding the draw method, the code is as follows:

 Public classCircleextendsShape {//Center Point    PrivatePoint Center; //radius    Private DoubleR;  PublicCircle (Point Center,Doubler) { This. Center =Center;  This. R =R; } @Override Public voidDraw () {System.out.println ("Draw circle at" +center.tostring () + "with R" +R+ ", using color:" +GetColor ()); }         Public DoubleArea () {returnmath.pi*r*R; }}

Explain the points:

    • Java uses the extends keyword to indicate an inheritance relationship, and a class can have at most one parent class.
    • Subclasses cannot directly access the private properties and methods of the parent class, for example, in circle, the private instance variable color of shape is not directly accessible.
    • In addition to private, subclasses inherit other properties and methods of the parent class, for example, in the draw method of circle, you can call the GetColor () method directly.

Look at the code that uses it:

 Public Static void Main (string[] args) {    new point (2,3);     // Create a circle, assign a value to circle    New Circle (center,2);     // call the Draw method to execute the draw method of Circle     Circle.draw ();     // Output Circle Area     System.out.println (Circle.area ());}

The output of the program is:

Draw circle at (2,3) with R 2.0, using Color:black12.566370614359172

What's strange here is, when is color assigned? In the process of new, the construction method of the parent class is also executed, and it takes precedence over the subclass to execute first. In this example, the default construction method of the parent shape is executed before the subclass Circle's construction method. The details of the new process are discussed further in the following sections.

Lines (line)

The line inherits from shape, but there are two points, there is a method to get the length, in addition, rewrite the draw method, the code is as follows:

 Public classLineextendsShape {PrivatePoint start; PrivatePoint end;  PublicLine (point start, point end, String color) {Super(color);  This. Start =start;  This. end =end; }     Public DoubleLength () {returnstart.distance (end); }         PublicPoint Getstart () {returnstart; }     PublicPoint getend () {returnend; } @Override Public voidDraw () {System.out.println ("Draw line from" + start.tostring () + "to" +end.tostring ()+ ", using color" +Super. GetColor ()); }}

Here we're going to explain the Super keyword, super is used to refer to the parent class , which can be used to call the parent class constructor method, access the parent class methods and variables:

    • In the line construction method, super (color) Represents the constructor method that calls the parent class with the color parameter, and the super (...) is called when the parent class constructs the method. Must be placed on the first line.
    • In the Draw method, Super.getcolor () means calling the GetColor method of the parent class, and of course not writing super. is also possible, because this method sub-class does not have the same name, no ambiguity, when there is ambiguity, through super. You can explicitly call the parent class.
    • Super can also refer to non-private variables of the parent class.

As you can see, super is used a bit like this, but super and this are different, this refers to an object that is actually present, can be used as a function parameter, can be returned as a value, but super is just a keyword, cannot be a parameter and a return value, it is just a related variable and method that tells the compiler to access the parent class.

Straight line with arrows (arrowline)

Lines with arrows are inherited from line, but there are two more properties, indicating whether there are arrows at both ends, and also rewrite the draw method, the code is as follows:

 Public classArrowlineextendsLine {Private BooleanStartarrow; Private BooleanEndArrow;  PublicArrowline (point start, point end, String color,BooleanStartarrow,BooleanEndArrow) {        Super(start, end, color);  This. Startarrow =Startarrow;  This. EndArrow =EndArrow; } @Override Public voidDraw () {Super. Draw (); if(Startarrow) {System.out.println ("Draw Start Arrow"); }        if(EndArrow) {System.out.println ("Draw End Arrow"); }    }}

Arrowline inherits from line, and the object that line inherits from Shape,arrowline also has the properties and methods of shape.

Note that the first line of the Draw method, Super.draw (), means that the draw () method of the parent class is called, without super at this time. No, because the current method is also called Draw ().

It should be explained that here Arrowline inherited line, can also be directly in the class line with attributes, and do not need to design a separate class Arrowline, here is mainly to demonstrate the hierarchy of inheritance.

Graphics Manager

One of the benefits of using inheritance is that objects of different subtypes can be processed uniformly, for example, let's look at a graphics manager class that manages all the graphical objects on the artboard and is responsible for drawing, and in drawing code, you just need to use each object as shape and call the Draw method. The draw method of the subclass is automatically executed. The code is as follows:

 Public classShapemanager {Private Static Final intMax_num = 100; Privateshape[] Shapes =NewShape[max_num]; Private intShapenum = 0;  Public voidAddShape (Shape shape) {if(shapenum<max_num) {Shapes[shapenum++] =shape; }    }         Public voidDraw () { for(inti=0;i<shapenum;i++) {Shapes[i].draw (); }    }}

Shapemanager uses an array to hold all the shapes and calls the draw method for each shape in the draw method. Shapemanager does not know the specific type of each shape, nor does it care, but can call the draw method to the subclass.

Let's take a look at an example of using Shapemanager:

 Public Static voidMain (string[] args) {Shapemanager manager=NewShapemanager (); Manager.addshape (NewCircle (NewPoint (BIS), 3)); Manager.addshape (NewLine (NewPoint (2,3),            NewPoint (3,4), "green")); Manager.addshape (NewArrowline (NewPoint (),             NewPoint (5,5), "Black",false,true)); Manager.draw ();}

Three new shapes, a circle, a line, and a line with arrows, are added to the shape manager and then the manager's draw method is called.

It is necessary to note that in the AddShape method, the Parameter shape shape, the declared type is shape, and the actual type is Circle,line and Arrowline, respectively. The subclass object assigns a value to the parent class reference variable, which is called upward transformation, transformation is the transformation type, and the upward transformation is converted to the parent class type.

Variable shape can refer to any object of shape subclass type, which is called polymorphic, a variable of one type, which can refer to many actual type objects. so, for the variable shape, it has two types, type shape, which we call shape static type , type Circle/line/arrowline, we call the dynamic type of shape. In the Shapemanager draw method, Shapes[i].draw () calls the draw method of its corresponding dynamic type, which is called the dynamic binding of the method .

Why should there be polymorphism and dynamic binding? The code that creates the object (code other than Shapemanager) and the Code of the operand (the code of the Shapemanager itself) are often not together, and the code that operates the object often knows only that the object is a certain type of parent, and often just needs to know that it is a certain type of parent.

It can be said that polymorphic and dynamic binding is an important way of thinking of computer programs, so that the procedure of manipulating objects does not need to pay attention to the actual types of objects, so it can deal with different objects uniformly, but can realize the unique behavior of each object. Next Chapters We will further describe the implementation of dynamic bindings.

Summary

This section describes the basic concepts of inheritance and polymorphism:

    • Each class has and has only one parent class, the parent class is not declared as object, the subclass inherits the parent class's non-private properties and methods, you can add your own properties and methods, you can override the parent class's method implementation.
    • In the new procedure, the parent class is initialized first, and the parent class's default constructor is invoked by super calling the corresponding constructor method of the parental class, without using Super.
    • The variables and methods of the parent class can be accessed by super when the subclass variables and methods have the same name as the parent class.
    • Subclass objects can be assigned to the parent class reference variable, which is called polymorphism, the actual execution of the call is a subclass implementation, which is called dynamic binding.

However, there are many details about inheritance, such as instances where the names of variables are identical. In addition, although inheritance can be reused code, to facilitate the uniform processing of different sub-categories of objects, but inheritance is actually a double-edged sword , improper use, there are many problems. Let's discuss these issues in the next section, and let's discuss the implementation principles of inheritance and polymorphism in the next section.

----------------

To be continued, check out the latest articles, please pay attention to the public number "old Horse Programming" (Scan the QR code below), from the introduction to advanced, in layman's words, Lao Ma and you explore the nature of Java programming and computer technology. Original article, All rights reserved.

Thinking Logic of computer program (15)-Initial knowledge inheritance and polymorphism

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.