首页 > 解决方案 > 从子类初始化私有变量

问题描述

我有一个即将举行的考试,其中一项练习任务如下:

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

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

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

详细描述:class Student使用两个私有对象变量namecourse. 然后创建一个构造函数来初始化这些变量、方法printname()printcourse()astract 方法printlabel()

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

例如

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

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

标签: javaprivate

解决方案


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


推荐阅读