【发布时间】:2019-02-14 10:55:05
【问题描述】:
我即将参加考试,其中一项练习任务如下:
我对这个任务的问题是两个私有变量 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();
}
详细说明:
使用两个私有对象变量name 和course 创建class Student。
然后创建一个构造函数来初始化这些变量,方法printname() 和printcourse() 以及抽象方法printlabel()。
然后创建两个子类Bachelor 和Master。他们应该有一个构造函数并覆盖抽象方法。
例如
Bachelor b = new Bachelor("James Bond", "Informatics");
b.printlabel();
应该返回名字、类名和课程。
【问题讨论】:
-
第一件事。在 Bechalor 的构造函数中使用
super(name, course). -
你的代码能编译吗? Student 类的构造函数必须命名为 Student(..) 而不是 Kata
-
在方法名中也使用驼峰命名
printname-->printName,printcourse-->printCourse -
@Jens 谢谢你。修正了错字。 :)
-
@Jens 关于 camelCase:我来自 Python,它更喜欢使用如下划线:print_name。这在 Java 中是可以接受的还是 camelCase 约定?