This is the 8th day of my participation in the August Text Challenge.More challenges in August

The article directories

  • inheritance
    • Example inheritance
    • A few notes on inheritance
  • Override ()
  • The Super keyword
  • Exercise: in two dimensional coordinates, find the distance from the origin
  • Exercise: the distance from the origin of a point in three-dimensional coordinates

inheritance

The three basic features of object orientation are encapsulation, inheritance and polymorphism. The next few articles will cover each of these basic features. Today we’re going to start with inheritance. Inheritance uses the extends keyword

Inheritance is when a subclass inherits the characteristics and behavior of its parent class, making its object (instance) have the instance fields and methods of its parent class, or a subclass inherits methods from its parent class, making it have the same behavior as its parent class. Code reuse can be achieved through inheritance.

A few notes: 1, the subclass has the parent class non-private attributes, methods. And subclasses can have their own properties and methods, that is, subclasses can extend their parent classes. Subclasses can implement the methods of their parent class in their own way. Constructors cannot be inherited and can be called using super(). A subclass calls its parent’s constructor by default, but if there is no default parent constructor, the subclass must display the specified parent’s constructor (via super()), and it must be called on the first line of code in the subclass constructor. Java inheritance is single-inheritance, that is, a subclass can have only one parent class, but a parent class can have multiple subclasses.

You can’t understand a bunch of theories, so let’s look at practical examples

Example inheritance

Ranging from students and staff: mankind students | — – | – employees

We create a Human Human class. The attributes of human beings are name, gender and age. At the same time we add the no-parameter and parameter-constructor and print the information separately.

public class Human {
    String name;
    String gender;
    int age;

    public Human(a) {
        Log.d("Inheritance"."Human()");
    }

    public Human(String name, String gender, int age) {
        this.name = name;
        this.gender = gender;
        this.age = age;
        Log.d("Inheritance"."The Human (1, 2, 3)");
    }

    public String tostring(a) {
        return "\n Name:" + name +
                "\n Gender:" + gender +
                "\n Age:"+ age; }}Copy the code

Let’s create a Student class Student class. The Student class has a human attribute and a school attribute.

public class Student extends Human {
    String school;
}
Copy the code

Let’s create an Employee class called Employee. Employee has human attributes as well as company attributes.

public class Employee extends Human {
    String company;
}
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="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="human" />

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

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="# 222222"
        android:textSize="18sp" />

</LinearLayout>
Copy the code

MainActivity

public class MainActivity extends AppCompatActivity {
    Button button1;
    Button button2;
    Button button3;
    TextView textView;

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

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

    public void doClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                f1();
                break;
            case R.id.button2:
                f2();
                break;
            case R.id.button3:
                f3();
                break; }}private void f1(a) {
        Human human = new Human("Beauty Ya"."Female".18);
        textView.setText(human.tostring());
    }

    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());
    }

    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()); }}Copy the code

Run the program:



And we can also see the Log output. Describes the parameterless constructor of the parent class that is called by default when a subclass object is created. For more details, see belowsuperIntroduction of keywords.

A few notes on inheritance

Initialize the parent class first and then the child class. Initialize the attributes of the object first, and then initialize the constructor.

Based on the above two points, we know that instantiating a subclass, Java program execution order is: parent object property initialization —-> parent object constructor —-> subclass object property initialization -> subclass object constructor

Using the example we started with, when the Student class is created, the Human class is actually created first (the parent class is created first and then the subclass is created). The Student and Human classes make up the complete Student class. 2. Subclasses call member variables, first looking for subclasses, then looking for the parent class

For example, when we call student.name we first look for the subclass to see if it has a name attribute, and if not, look for the parent class.

3. By default, subclasses call the parent class with no arguments constructor

We can add a constructor to the Student class that calls the parent class’s parameterless constructor by default, either with or without arguments:

  public Student(String name,String gender,int age,String school){
		//super(); // This is the default sentence
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.school = school;
    }

    public Student(a){
		//super(); By default, the parent class is called with no arguments constructor
    }
Copy the code

4. Subclasses can also call the parent class parameter constructor manually

For example, in the Student constructor, the parent class parameter constructor is called manually:

    public Student(String name,String gender,int age,String school){
        super(name,gender,age);
        this.school = school;
    }

    public Student(a){}Copy the code

Override ()

When an inherited method does not meet the needs of a subclass, you can rewrite the method in a subclass. As in the previous example, the toString () method in Human prints the name, gender, and age. But the special property school in the student class and the special property company in the employee class are not printed, so we need to override the toString () method.

If you rewrite the toString () method in a subclass, then the subclass calls toString () and executes the tostirng() method in the subclass

Student class

public class Student extends Human {
    String school;

    public String tostring(a) {
        return "\n Name:" + name +
                "\n Gender:" + gender +
                "\n Age:" + age +
                "\n School:"+ school; }}Copy the code

The Employee class

public class Employee extends Human {
    String company;

    public String tostring(a) {
        return "\n Name:" + name +
                "\n Gender:" + gender +
                "\n Age:" + age +
                "\ N Corporation:"+ company; }}Copy the code

Run the program again:

When overriding a parent class method, use super.xx(); Code that calls the same method as the parent class avoids code duplication, for example:

public class Employee extends Human {
    String company;

    public String tostring(a) {
        return super.tostring() +
                "\ N Corporation:"+ company; }}Copy the code

1, the return value type, method name parameter type and number should be the same as the parent class inherited method, is the method rewrite. 2. A method ina parent class that uses a private, static, or final modifier cannot be overridden by a subclass. These keywords will be introduced in later articles.

The difference between overloading and overwriting

The mark Overloaded methods Overriding methods
The list of parameters Must be modified It must not be modified
The return type You can modify It must not be modified
abnormal You can modify You can reduce or delete exceptions, and must not throw new or broader exceptions
access You can modify It must not be more restrictive (it can be lower)

The Super keyword

You can think of it as a reference to the parent class, using super to call the properties, methods, and constructors of the parent class.

We know that subclass construction must call the parent class constructor. In fact, this process already implicitly uses our super keyword. This is because the constructor that calls the parent class without arguments is called by default if the constructor of the child class does not show up in the constructor of the child class.

If you call the parent constructor in a subclass with the super keyword, it must be on the first line in the subclass constructor.

Note that a compilation error occurs if the subclass constructor shows no constructor that calls the parent class, and the parent class has no constructor that takes no arguments. Add a parameterless constructor to the parent class. 2. Call the parent class’s parameterized constructor manually from a subclass, such as super(parameter).

(Note: if you declare a constructor with arguments and do not declare a constructor with no arguments, the system does not generate a constructor with no arguments by default.)

Exercise: in two dimensional coordinates, find the distance from the origin

Start by creating a Point class that represents coordinate points in terms of x and y

public class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public String tostring(a) {
        return "(" + x + "," + y + ")";
    }

    public double distance(a) {
        return Math.sqrt(x * x + y * y);
    }

	public double distance(Point p) {
        x = p.x;
        y = p.y;
        returndistance(); }}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">

    <EditText
        android:id="@+id/xEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="x" />

    <EditText
        android:id="@+id/yEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="y" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="Distance to the origin" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="# 222222"
        android:textSize="18sp" />

</LinearLayout>
Copy the code

MainActivity

public class MainActivity extends AppCompatActivity {
    EditText xEditText;
    EditText yEditText;
    Button button1;
    TextView textView;

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

        xEditText = findViewById(R.id.xEditText);
        yEditText = findViewById(R.id.yEditText);
        button1 = findViewById(R.id.button1);
        textView = findViewById(R.id.textView);
    }

    public void doClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                f1();
                break; }}private void f1(a) {
        String x = xEditText.getText().toString();
        String y = yEditText.getText().toString();
        Point point = new Point(Integer.parseInt(x), Integer.parseInt(y));
        textView.setText(point.tostring() + "\n"+ point.distance()); }}Copy the code

Run the program:

Exercise: the distance from the origin of a point in three-dimensional coordinates

We can expand on what we just did. There is an extra Z-axis in 3d coordinates compared to 2d coordinates, so we can create a Point3D class to inherit the Point class

Point3D class

public class Point3D extends Point {
    int z;

    public Point3D(int x, int y) {
        super(x, y);
    }

    public Point3D(int x, int y, int z) {
        super(x, y);
        this.z = z;
    }

    @Override
    public String tostring(a) {
        return "(" + x + "," + y + "," + z + ")";
    }

    @Override
    public double distance(a) {
        return Math.sqrt(x * x + y * y + z * z);
    }

    @Override
    public double distance(Point p) {
        return super.distance(p); }}Copy the code

XML adds an Edittext for the z-axis coordinates and a Button for the distance to the origin below the original Button

<EditText
        android:id="@+id/zEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="z" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="doClick"
        android:text="3d" />
Copy the code

In MainActivity, we modify the original code. The first button not only calculates the distance between the coordinate point and the origin, but also calculates the distance to the random coordinate. At the same time, the method of distance from the point to the origin in 3d coordinates is added:

public class MainActivity extends AppCompatActivity {
    EditText editText1;
    EditText editText2;
    EditText editText3;
    Button button1;
    Button button2;
    TextView textView;

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

        editText1 = (EditText) findViewById(R.id.xEditText);
        editText2 = (EditText) findViewById(R.id.yEditText);
        editText3 = (EditText) findViewById(R.id.zEditText);
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        textView = (TextView) findViewById(R.id.textView);
    }

    public void doClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                f1();
                break;
            case R.id.button2:
                f2();
                break; }}private void f2(a) {
        int x = Integer.parseInt(editText1.getText().toString());
        int y = Integer.parseInt(editText2.getText().toString());
        int z = Integer.parseInt(editText3.getText().toString());
        Point3D point3D = new Point3D(x, y, z);
        textView.append(point3D.tostring() + "Distance from the origin" + point3D.distance() + "\n");
    }

    private void f1(a) {
        int x = Integer.parseInt(editText1.getText().toString());
        int y = Integer.parseInt(editText2.getText().toString());
        Point point1 = new Point(x, y);
        textView.setText(point1.tostring() + "Distance from the origin" + point1.distance() + "\n");

        Point point2 = new Point(new Random().nextInt(10), new Random().nextInt(10));
        textView.append(point1.tostring() + "Distance" + point2.tostring() + "Distance is:" + point1.distance(point2) + "\n"); }}Copy the code

Run the program: