从子类初始化私有变量

问题描述 投票:1回答:2

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

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

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

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 Studentname创建course。然后创建一个初始化这些变量的构造函数,方法printname()printcourse()以及astract方法printlabel()

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

EG

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

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

java private
2个回答
1
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.