java 在同一个类中,其类对象之间私有成员的访问

在同一个类中,其类对象之间私有成员的访问
定义一个表示学生信息的Student 类,Student 类中包含表示学生姓名和分数的私有成员变量,定义一个用于比较学生成绩的方法isEqualTo,若学生A的分数比B更高,输出The student A is more excellent!,若学生B的分数比A更高,输出The student B is more excellent!,否则,输出Student A and B are all excellent!
输出:若创建学生姓名为ZhanSan,分数为91和学生姓名为LiSi,分数为86的两个学生对象,程序的输出结果如下:
The student ZhanSan is more excellent!


```java


```

该回答引用NewBing

你好,这是Bing。😊


根据我的搜索结果¹²³,在同一个类中,其类对象之间可以访问私有成员,因为它们属于同一个作用域。私有成员只对类外部的其他类或对象不可见。


你的题目要求定义一个表示学生信息的Student 类,其中包含姓名和分数的私有成员变量,并定义一个用于比较学生成绩的方法isEqualTo。我可以为你生成一段可能的代码示例,但请注意这不一定是唯一正确的答案。

// 用code blocks语法封装代码示例
public class Student {
    // 声明私有成员变量
    private String name;
    private int score;

    // 定义构造方法
    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    // 定义比较学生成绩的方法
    public void isEqualTo(Student other) {
        if (this.score > other.score) { // 可以访问other对象的私有成员score
            System.out.println("The student " + this.name + " is more excellent!");
        } else if (this.score < other.score) {
            System.out.println("The student " + other.name + " is more excellent!");
        } else {
            System.out.println("Student " + this.name + " and " + other.name + " are all excellent!");
        }
    }

    public static void main(String[] args) {
        // 创建两个学生对象
        Student s1 = new Student("ZhanSan", 91);
        Student s2 = new Student("LiSi", 86);
        // 调用isEqualTo方法比较两个学生对象的分数
        s1.isEqualTo(s2);
    }
}

源: 与必应的对话, 2023/3/21

先写一个Student类,注意定义私有变量之后,写上构造函数和getter、setter方法。

class Student {
    private String name;
    private int score;
    public Student() {
        super();
    }
    public Student(String name, int score) {
        super();
        this.name = name;
        this.score = score;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getScore() {
        return score;
    }
    public void setScore(int score) {
        this.score = score;
    }
}

然后写测试类,主方法main()里面写主程序,另外为方便起见,可以将要写的isEqualTo()定义成static方法,这样便于调用。

public class TestStudent {
    public static String isEqualTo(Student A, Student B){
        int a = A.getScore();
        int b = B.getScore();
        if(a>b){
            return "The student "+A.getName()+" is more excellent!";
        }else if(a<b){
            return "The student "+B.getName()+" is more excellent!";
        }else{
            return "Student "+A.getName()+" and "+B.getName()+" B are all excellent!";
        }
    }
    public static void main(String[] args) {
        Student A = new Student("ZhanSan", 91);
        Student B = new Student("LiSi", 86);
        String result = isEqualTo(A,B);
        System.out.println(result);
    }
}