This is the 9th day of my participation in the August Wen Challenge.More challenges in August

The article directories

  • Definition and Function
  • How to implement polymorphism
  • Example 1: Human class
  • The instanceof keyword
  • Example 2: The Point3D class
  • Example 3: Drawing graphics
  • Type conversion

Definition and Function

The definition of polymorphism is object-oriented polymorphism, or “one interface, many methods”. Polymorphism is embodied in the fact that the attributes and methods defined in the parent class can have different attributes or manifestations after being inherited by the subclasses.

The function of polymorphism 1, can directly put different subclasses when the parent class (multiple seed types can be converted into a consistent parent type), shielding the differences between subclasses, improve the code of the general rate/reuse rate 2, parent class reference can call the function of different subclasses, improve the code expansion and maintainability

How to implement polymorphism

There are three necessary conditions for Java to implement polymorphism: inheritance, rewriting, and upward transition.

Inheritance: In polymorphism, there must be a subclass and a parent class that have an inheritance relationship. Override: A subclass redefines methods in its parent class that are called when those methods are called. Upward transition: In polymorphism, a reference to a subclass is assigned to a superclass object so that the reference has the ability to call methods of the parent class and methods of the subclass

Example 1: Human class

We use the Human class example from the previous chapter (Portal: Object-oriented Inheritance and Rewriting).

Humans ranging from students and staff: name, gender, age | – students: in addition to human property, specific attribute also school | – employees: in addition to human property, company also has a unique attribute

We have three classes Human, Student, and Employee. Each class has its own toString() method to output its own attributes.

The MainActivity code remains the same.

public class MainActivity extends AppCompatActivity {...private void f1(a) {
        Human human = new Human("Beauty Ya"."Female".18);
        //textView.setText(human.tostring());

        f(human);
    }

    private void f2(a) {
        Student student = new Student();
        student.name = "A";
        student.gender = "Male";
        student.age = 10;
        student.school = "Peking University";
        //textView.setText(student.tostring());
        // The student type is upcast to Human type, passed to the f() method
        f(student);
    }

    private void f3(a) {
        Employee employee = new Employee();
        employee.name = "Small B";
        employee.gender = "Female";
        employee.age = 22;
        employee.company = "JiChun";
        //textView.setText(employee.tostring());

        f(employee);
    }

    /* * All subtype objects can be converted to the parent type and passed to this method for processing * If the parent type is passed, toString () of the parent type is called directly; Method * calls toString () of a subtype if it is passed; Methods * * /
    void f(Human human) {
        textView.append("\n"+ human.tostring()); }}Copy the code

If I run f(2); When, add a breakpoint, you can see to pass to f(Human Human); The Student type is in the method



Run the program:

The instanceof keyword

It tests whether the object to its left is an instance of the class to its right and returns Boolean data. This is used to check whether an object is an instance of a class. Returns true and false.

Example 2: The Point3D class

We use the Point3D class example from the previous chapter (Portal: Object-oriented Inheritance and Rewriting)

We have a Point class that can find the distance from the origin of a Point in two dimensional coordinates. We added a Point3D class that inherits the Point class. In addition to calculating the distance from the origin of a point in two-dimensional coordinates, you can also calculate the distance from the origin of a point in three-dimensional coordinates

Modify the method distance(Point P) in the Point3D class to determine whether the Point type passed in is two-dimensional coordinate or three-dimensional coordinate.

public class Point3D extends Point {...@Override
    public double distance(Point p) {
        int dx = x - p.x;
        int dy = y - p.y;
        int dz;

        // The current point is a three-dimensional point
        // Find the distance from the parameter point p, which can also be two-dimensional or three-dimensional
        // We need to determine whether p is two-dimensional or three-dimensional
        if (p instanceof Point3D) {
            // After an upward transition, only the generic members defined by the parent class can be called
            Subclass-specific members cannot be called
            // We can call it back to a subtype first
            dz = z - ((Point3D) p).z;
        } else {
            dz = z;
        }
        returnMath.sqrt(dx * dx + dy * dy + dz * dz); }}Copy the code

Example 3: Drawing graphics

We have Shape, whose subclasses are Line, Circle, and Square:

Shape: the draw (drawing), clean (clear) | – Line: have their own draw method. Have separate | – Circle: length method has its own | – Square: the draw method has its own draw method

Share

public class Shape {
    public void draw(TextView view) {
        // Meaningless code that will be overridden in subclasses
        view.setText("Graphics");
    }

    public void clean(TextView view) {
        view.setText(""); }}Copy the code

Line

public class Line extends Shape {
    @Override
    public void draw(TextView view) {
        super.draw(view);
        view.setText("-");
    }

    public void length(TextView view) {
        view.append("\ N line is very very long..."); }}Copy the code

Circle

public class Circle extends Shape {
    @Override
    public void draw(TextView view) {
        super.draw(view);
        view.setText("o"); }}Copy the code

Square

public class Square extends Shape {
    @Override
    public void draw(TextView view) {
        super.draw(view);
        view.setText("Mouth"); }}Copy the code

xml


      
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Shape" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Line" />

    <Button
        android:id="@+id/button3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Circle" />

    <Button
        android:id="@+id/button4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Squre" />

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Erase" />

	<TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="# 222222"
        android:gravity="center"/>
</LinearLayout>
Copy the code

MainActivity

public class MainActivity extends AppCompatActivity {
    Button button1;
    Button button2;
    Button button3;
    Button button4;
    Button button5;
    TextView textView;
    private Shape currentShape;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.text);
        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        button3 = findViewById(R.id.button3);
        button4 = findViewById(R.id.button4);
        button5 = findViewById(R.id.button5);
    }

    public void doClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                f(new Shape());
                break;
            case R.id.button2:
                f(new Line());
                break;
            case R.id.button3:
                f(new Circle());
                break;
            case R.id.button4:
                f(new Square());
                break;
            case R.id.button5:
                f1();
                break; }}private void f(Shape shape) {
        // Parameter object, save to member variable
        currentShape = shape;
        shape.draw(textView);
        // Only the generic members defined by the parent class can be accessed after the upward transition
        // Cannot access subclass-specific members
        //shape.length();
        if (shape instanceofLine) { Line line = (Line) shape; line.length(textView); }}private void f1(a) {
        if(currentShape ! =null) {
            currentShape.clean(textView);
            currentShape = null; }}}Copy the code

Run the program:

Type conversion

Two of these examples have an upward transition in the comments. To explain, an upcast is when a subclass object is converted to a parent type. The format is as follows:

Superclass Superclass object = instance of a subclass; (Automatic conversion)

For example, we can pass in subclasses new Line(), new Circle(), and so on

The characteristics of upward transformation are as follows: 1. After upward transformation, only general members defined by the parent class can be called. 2

A downward cast is when a subclass object that has been cast to a parent type is cast back to a subtype. The format is as follows:

Subclass object = (subclass) instance of the parent class; (Cast)

As in the drawing example above, the f() method takes Shape, but to call subclass-specific methods, we need to force the subclass type: Line Line = (Line) Shape;