When multiple classes have the same attributes, consider using inheritance and interfaces to optimize the code

inherit

If there are common attributes among multiple classes, you can create a parent class, define these attributes in the parent class, and then let these classes inherit the parent class, so as to avoid repeatedly defining attributes in each class.

public class Person {
    protected String name; // 共同的属性

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public class Student extends Person {
    private int grade; // 学生特有的属性

    // 学生特有的方法
    public void setGrade(int grade) {
        this.grade = grade;
    }

    public int getGrade() {
        return grade;
    }
}

public class Teacher extends Person {
    private String subject; // 教师特有的属性

    // 教师特有的方法
    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getSubject() {
        return subject;
    }
}

In the above example, the Person class defines a common attribute name, and the Student class and the Teacher class respectively inherit the Person class, thus having a common attribute. This avoids repeating the definition of the name attribute in the Student and Teacher classes.

interface

If the same behavior exists for multiple classes, you can use an interface to define these behaviors, and then have those classes implement the interface. The access method of the attribute can be defined in the interface

public interface Identifiable {
    String getId(); // 声明获取ID的方法
}

public class Student implements Identifiable {
    private String id; // 学生特有的属性

    // 实现接口定义的方法
    public String getId() {
        return id;
    }
}

public class Teacher implements Identifiable {
    private String id; // 教师特有的属性

    // 实现接口定义的方法
    public String getId() {
        return id;
    }
}

In the above example, the Identifiable interface defines the method for obtaining the ID, and both the Student class and the Teacher class implement this interface and implement the method for obtaining the ID. This uniformly defines the same behavior and avoids duplication of code.

By using inheritance and interfaces, you can optimize your code, avoid repeating the definition of the same property, and improve the maintainability and reusability of your code. At the same time, it can better conform to the object-oriented design principles and improve the encapsulation and scalability of the code.

Guess you like

Origin blog.csdn.net/weixin_43866250/article/details/131954004