gpt4 book ai didi

java - 如何访问继承中的私有(private)字段

转载 作者:行者123 更新时间:2023-12-01 22:31:56 24 4
gpt4 key购买 nike

假设我有一个类名Employee

class Employee
{
int empID;
String name;
public Employee(int empID,String name)
{
this.empID = empID;
this.name = name;
}
// getters and setters
}

现在我根据他们的位置创建子类

class Manager extends Employee
{
private String salary;
private int deptID;
public Manager(String salary, int deptID,int id, String name)
{
super(id,name);
this.salary = salary;
this.deptID = deptID;
}
// getters and setters
}

如果我想从 Manager 类访问 Manager 的 empID 和名称,我该怎么做,因为这些字段是私有(private)的?我在想在 Manager 类的 getter 函数中,我会做 super.getName() 和 super.getID() 吗?

如果类设计模式有任何错误,请告诉我。我想让它尽可能完美。感谢您的帮助。

最佳答案

如果您使用 protected 变量,则任何继承它们的类都可以访问它们。

class Employee
{
protected int empID;
protected String name;
public Employee(int empID,String name)
{
this.empID = empID;
this.name = name;
}
}

class Manager extends Employee
{
private String salary;
private int deptID;
public Manager(String salary, int deptID,int id, String name)
{
super(id,name);
this.salary = salary;
this.deptID = deptID;

// Can access protected variables
empID = 0;
}
}

否则,您可以将 getter 和 setter 与 protected 或 public 访问器一起使用,并将变量标记为私有(private)。

当前您的变量被标记为默认值(没有指定的访问器)您可以在此处查看不同的访问器允许您执行的操作:http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

关于java - 如何访问继承中的私有(private)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27583354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com