我即将开始考试,其中一项练习任务如下:
我的这个任务的问题是两个私有变量名称和课程。私有意味着它们不能被子类覆盖,对吗?我该如何从子类初始化这些变量?
到目前为止这是我的代码,但它不起作用:
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
和name
创建course
。然后创建一个初始化这些变量的构造函数,方法printname()
和printcourse()
以及astract方法printlabel()
。
然后创建两个子类Bachelor
和Master
。他们应该有一个构造函数并覆盖抽象方法。
EG
Bachelor b = new Bachelor("James Bond", "Informatics");
b.printlabel();
应该返回名称,类名和课程。
您可以使用a call to super()
访问超类构造函数。因此,在您的子类中,只需调用super(n, c);
而不是直接分配变量,您应该获得预期的行为。
添加一个设置私有属性的公共方法。从构造函数调用所述公共方法。