Three major characteristics of Java object-oriented - inheritance (extends)

Inheritance is one of the three major characteristics of object-oriented. The similarity between inheritance and "inheritance" in real life is that some characteristics of the parent are retained, thereby reducing code redundancy and improving program running efficiency.

Inheritance in Java  is to extend existing classes to create new classes. An existing class is called a parent class, base class or super class, and a newly generated class is called a subclass or derived class. In a subclass, not only the properties and methods of the parent class are included, but new properties and methods can also be added.

The syntax format for subclass inheritance from parent class in Java is as follows:

修饰符 class class_name extends extend_class {
// 类的主体
}

Among them, class_name represents the name of the subclass (derived class); extend_class represents the name of the parent class (base class); the extends keyword directly follows the subclass name, followed by the name of the parent class to be inherited by the class. For example:

public class Student extends Person{}

Inheritance in Java is implemented through the extends keyword. The English meaning of extends is extension, not inheritance. extends well reflects the relationship between subclasses and parent classes, that is, subclasses are extensions of parent classes, and subclasses are a special parent class. From this perspective, it is wrong to use inheritance to describe the relationship between subclasses and parent classes, and extension is more appropriate.

So why is extends translated as “inheritance” in China? After the subclass extends the parent class, it can obtain the attributes and methods of the parent class, which is similar to inheritance in Chinese (the subclass obtains a fortune from the parent class, which is called inheritance).

The way Java and  C++  define inherited classes is very similar. Java uses the keyword extends instead of the colon (:) in C++. In Java, all inheritance is public inheritance, and there is no private inheritance and protected inheritance in C++.

Inheritance of a class does not change the access rights of class members. That is to say, if the members of the parent class are public, protected or default, its subclasses still have the corresponding characteristics, and the subclass cannot obtain the parent class's Construction method.

Example 1

Teachers and students are both human beings. They have common attributes: name, age, gender and ID number. Students also have two attributes: student number and major. Teachers also have two attributes: teaching experience and major. Write the Java program code below so that both the Teacher class and the Student class inherit from the People class. The specific implementation steps are as follows.

1) Create human People and define name, age, sex, sn attributes. The code is as follows:

public class People {

    public String name; // 姓名
    public int age; // 年龄
    public String sex; // 性别
    public String sn; // 身份证号

    public People(String name, int age, String sex, String sn) {
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.sn = sn;
    }

    public String toString() {
        return "姓名:" + name + "\n年龄:" + age + "\n性别:" + sex + "\n身份证号:" + sn;
    }
}

As shown in the above code, the People class contains 4 public properties, a constructor and a toString() method.

2) Create the Student class, a subclass of the People class, and define the stuNo and department attributes. The code is as follows

public class Student extends People {
    private String stuNo; // 学号
    private String department; // 所学专业

    public Student(String name, int age, String sex, String sn, String stuno, String         department) {
        super(name, age, sex, sn); // 调用父类中的构造方法
        this.stuNo = stuno;
        this.department = department;
    }

    public String toString() {
        return "姓名:" + name + "\n年龄:" + age + "\n性别:" + sex + "\n身份证号:" + sn + "\n学    号:" + stuNo + "\n所学专业:" + department;
    }
}

Since the Student class inherits from the People class, the Student class also has the properties and methods of the People class. The toString() method in the parent class is overridden here.

Note: If there is a parameterized constructor in the parent class and there is no overloaded parameterless constructor, then the parameterized constructor must be included in the subclass, because if there is no constructor in the subclass, it will be used by default. Calling the parameterless constructor in the parent class, but there is no parameterless constructor in the parent class, so an error occurs.

3) Create another subclass of the People class, Teacher, and define the tYear and tDept attributes. The code is as follows:

public class Teacher extends People {
    private int tYear; // 教龄
    private String tDept; // 所教专业

    public Teacher(String name, int age, String sex, String sn, int tYear, String tDept) {
    super(name, age, sex, sn); // 调用父类中的构造方法
    this.tYear = tYear;
    this.tDept = tDept;
    }

    public String toString() {
        return "姓名:" + name + "\n年龄:" + age + "\n性别:" + sex + "\n身份证号:" + sn +     "\n教龄:" + tYear + "\n所教专业:" + tDept;
    }
}

The Teacher class is similar to the Student class and also overrides the toString() method in the parent class.

4) Write the test class PeopleTest, create different objects of the People class in this class, call their toString() methods respectively, and output different information. The specific code is as follows:

public class PeopleTest {
    public static void main(String[] args) {
    // 创建Student类对象
    People stuPeople = new Student("王丽丽", 23, "女", "410521198902145589", "00001", "计算    机应用与技术");
    System.out.println("----------------学生信息---------------------");
    System.out.println(stuPeople);

    // 创建Teacher类对象
    People teaPeople = new Teacher("张文", 30, "男", "410521198203128847", 5, "计算机应用与技    术");
    System.out.println("----------------教师信息----------------------");
    System.out.println(teaPeople);
    }
}

Run the program and the output results are as follows:

----------------Student Information-------------------------- 
Name: Wang Lili 
Age: 23 
Gender: Female 
ID card No.: 410521198902145589 
Student No.: 00001 
Major: Computer Application and Technology 
----------------Teacher Information----------------- ----- 
Name: Zhang Wen 
Age: 30 
Gender: Male 
ID number: 410521198203128847 
Teaching years: 5 
Teaching major: Computer application and technology

Single inheritance

The Java language abandons the difficult-to-understand multiple inheritance feature in C++, that is, Java does not support multiple inheritance, and only allows one class to directly inherit another class, that is, a subclass can only have one direct parent class, and there can only be one class after the extends keyword. name. For example, the following code will cause a compilation error:


class Student extends Person,Person1,Person2{…}

class Student extends Person,extends Person1,extends Person2{…}

Extension : implements can be implemented in multiple ways, that is, there can only be one class name after the implements keyword. For example, the following code compiles normally:


class Student implements Person,Person1,Person2{…}

class Student extends Person implements Person1, Person2{…}


When introducing Java's single inheritance in many places, it may be said that a Java class can only have one parent class. Strictly speaking, this statement is wrong. It should be that a class can only have one direct parent class, but it can have multiple an indirect parent class . For example, the Student class inherits the Person class, the Person class inherits the Person1 class, and the Person1 class inherits the Person2 class, then the Person1 and Person2 classes are indirect parent classes of the Student class. Figure 1 shows the relationship of single inheritance.


Figure 1 Relationship between graphics classes


As can be seen from Figure 1, the direct parent class of triangles, quadrilaterals and pentagons is the polygon class, and their indirect parent class is the graphics class. Graphics classes, polygon classes, and triangle, quadrilateral, and pentagon classes form an inheritance branch. On this branch, the subclasses located in the lower layer will inherit the properties and methods of all direct or indirect parent classes in the upper layer. If two classes are not on the same inheritance tree branch, there will be no inheritance relationship, such as the polygon class and the line.

If you define a Java class without explicitly specifying the direct parent class of the class, the class inherits from the java.lang.Object class by default. Therefore, the java.lang.Object class is the parent class of all classes, either their direct parent class or their indirect parent class. Therefore, all Java objects can call instance methods defined by the java.lang.Object class.

Notes on using inheritance :

  1. Subclasses generally contain more properties and methods than parent classes.
  2. Private members in the parent class are not visible in the child class, so they cannot be used directly in the child class.
  3. There must be an "is-a" relationship between the parent class and its subclasses, otherwise inheritance cannot be used. But not everything that conforms to the "is-a" relationship should use inheritance. For example, a square is a rectangle, but the square class cannot inherit the rectangle class because a square cannot extend anything from a rectangle. The correct inheritance relationship is that the square class inherits the graphics class.
  4. Java only allows single inheritance (that is, a subclass can only have one direct parent class), and C++ can multiple inheritance (that is, a subclass can have multiple direct parent classes).
Advantages and disadvantages of inheritance:
  1. Implement code sharing, reduce the workload of creating classes, and enable subclasses to have the methods and attributes of the parent class.
  2. Improve code maintainability and reusability.
  3. Improve the scalability of the code and better implement the parent class method.


Disadvantages of inheritance:

  1. Inheritance is intrusive. As long as you inherit, you must have the properties and methods of the parent class.
  2. Reduce code flexibility. Subclasses have more constraints after possessing the properties and methods of the parent class.
  3. Enhance code coupling (the principle of development projects is high cohesion and low coupling). When the constants, variables and methods of the parent class are modified, the modifications of the subclass need to be considered, which may cause large sections of code to be refactored.

Guess you like

Origin blog.csdn.net/ddwangbin520/article/details/131450138