当前位置: 代码迷 >> java >> 从子类初始化私有变量
  详细解决方案

从子类初始化私有变量

热度:40   发布时间:2023-07-31 11:50:57.0

我即将参加考试,其中一项练习任务如下:

我对这个任务的问题是两个私有变量 name 和 course。 私有意味着它们不能被子类覆盖,对吗? 我应该如何从子类初始化这些变量?

到目前为止,这是我的代码,但它不起作用:

class Bachelor extends Student{
    Bachelor (String n, String c){
        name = n;
        course = c;
    }
    void printlabel() {
        System.out.println("%s\nBachelor %s",name, course);
    }
}
class Master extends Student{
    Master (String n, String c){
        name = n;
        course = c;
    }
    void printlabel() {
        System.out.println("%s\nMaster %s",name, course);
    }
}

public abstract class Student {
    private String name;
    private String course;
    public Student (String n, String c) {
        name = n;
        course = c;
    }
    void printname() {
        System.out.println(name);
    }
    void printcourse() {
        System.out.println(course);
    }

    public static void main(String[] args) {
        Bachelor rolf = new Bachelor("Rolf", "Informatics");
        rolf.printname();

    }
    abstract void printlabel();
}

详细说明:创建具有两个私有对象变量namecourse class Student 然后创建一个构造函数来初始化这些变量,方法printname()printcourse()以及 astract 方法printlabel()

然后创建两个子类BachelorMaster 他们应该有一个构造函数并覆盖抽象方法。

例如

Bachelor b = new Bachelor("James Bond", "Informatics");
b.printlabel();

应该返回名称、类名和课程。

您可以通过 来访问超类构造函数。 所以在你的子类中,只需调用super(n, c); 而不是直接分配变量,你应该得到预期的行为。

添加设置私有属性的公共方法。 从构造函数调用所说的公共方法。

  相关解决方案