【问题标题】:Initialize private variables from subclass从子类初始化私有变量
【发布时间】: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();
}

详细说明: 使用两个私有对象变量namecourse 创建class Student。 然后创建一个构造函数来初始化这些变量,方法printname()printcourse() 以及抽象方法printlabel()

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

例如

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 约定?

标签: java private


【解决方案1】:

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

【讨论】:

  • 谢谢。这帮助我解决了这个问题。凭借这些知识,我在考试中获得的任何分数都将是您的荣幸! :D 我会 +1 你的答案,但不幸的是我现在缺乏这点。当我有它们时会回来。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 2014-08-15
    • 2016-07-22
    • 2022-01-13
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    相关资源
    最近更新 更多