java - 从子类初始化私有变量
问题描述
我有一个即将举行的考试,其中一项练习任务如下:
我对这个任务的问题是两个私有变量名称和课程。私有意味着它们不能被子类覆盖,对吗?我应该如何从子类中初始化这些变量?
到目前为止,这是我的代码,但它不起作用:
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
. 他们应该有一个构造函数并覆盖抽象方法。
例如
Bachelor b = new Bachelor("James Bond", "Informatics");
b.printlabel();
应该返回名称、类名和课程。
解决方案
您可以通过调用来super()
访问超类构造函数。因此,在您的子类中,只需调用super(n, c);
而不是直接分配变量,您应该会得到预期的行为。
推荐阅读
- ios - 当应用程序为背景时如何添加图像
- python - pygame.sprite.Group.draw 不绘制图像
- java - 如何为打包安装程序(使用 Jpackage 创建)安装的 java 应用程序设置自定义安装目录?
- spring-boot - Spring REST:在 RestTemplate 与 RequestEntity 中指定 http 方法和 url
- azure - 基于读取 Odata 的 Azure 警报
- android - 为回收站视图的项目视图设置可访问性操作
- google-cloud-platform - GCP 警报过滤器不影响公开事件
- pygame - 如何返回类中立方体的位置值?
- oracle-nosql - Oracle NoSQL 数据库我在 JConsole 中看不到 JMX 统计信息
- vue.js - 如何使用 axios 和代理获取 api 数据?