【问题标题】:How private variables in superclass is inherited in the subclass here? [duplicate]超类中的私有变量如何在这里的子类中继承? [复制]
【发布时间】:2019-02-19 22:03:50
【问题描述】:
package practice;

class person{
private String firstname;
private String lastname;

public person(String firstname,String lastname){
    set_first(firstname);
    set_last(lastname);
}

public String get_first() {
    return firstname;
}
public void set_first(String firstname) {
    this.firstname=firstname;
}
public void set_last(String lastname) {
    this.lastname=lastname;
}
public String get_last() {
    return lastname;
}
}

class employee extends person{  
private int empid;  
public employee(String firstname,String lastname,int empid){  
    super(firstname,lastname);  
    set_empid(empid);
}

public void set_empid(int empid) {
    this.empid=empid;
}
public int get_empid() {
    return empid;
}
}

class testing_super_keyword {  
public static void main(String args[]) {  
    employee emp=new employee("John","Jackson",1234);  
    System.out.println(emp.get_first()+"  "+emp.get_last());  
    System.out.println(emp.get_empid());  
}
}

任何人都可以解释类员工如何继承类人,即使类人“名字”和“姓氏”的属性已被声明为私有?

据我所知,声明为私有的超类变量不能被子类继承。

【问题讨论】:

    标签: java


    【解决方案1】:

    这被认为是一种良好的编程习惯,您无需使用private access specifiers 直接访问类的实例变量,而是提供public getter and setter methods 来获取和设置实例变量。

    在您的情况下,您无法直接访问 SuperClass 的实例变量,但您声明了 public getter and setter methods(get_first, set_first) 并且可以使用它们。

    此外,根据 Java 命名约定,函数使用驼峰命名法。例如,而不是 get_name 使用 getName 和儿子。

    【讨论】:

      猜你喜欢
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 2018-06-14
      相关资源
      最近更新 更多