【问题标题】:When creating a superclass and child class, do class fields of both the parent and child class need to be public in order for them to work together? [duplicate]在创建超类和子类时,父类和子类的类字段是否需要公开才能使它们协同工作? [复制]
【发布时间】:2021-06-20 08:03:35
【问题描述】:

我正在使用 Java 创建一个简单的 Employee 类,其中 Production Worker 作为子类。我将两个类字段都设置为私有,但我只想知道它们是否需要公开。我知道当使用私有字段时,它会使其对其他超类保持私有,但它对于继承是否同样有效?预先感谢您提供帮助。代码如下

package Employee;



public class Employee {
    
    // declare employee class fields
    private String empName;
    private String empId;
    private String hireDate;
    
    // default constructor
    public Employee()
    {
        empName = "";
        empId = "";
        hireDate = "";
        
    }
    // constructor with arguments passed in
    public Employee(String name, String id, String date)
    {
        empName = name;
        empId = id;
        hireDate = date;
    }
    
    // set methods for employee class
    public void setEmpName(String name)
    {
        empName = name;
    }
    public void setEmpID(String id)
    {
        empId = id;
    }
    public void setHireDate(String date)
    {
        hireDate = date;
    }
    
    // get methods for employee class
    public String getName()
    {
        return empName;
    }
    public String getID()
    {
        return empId;
    }
    public String getDate()
    {
        return hireDate;
    }
    
    // create production worker class; child to employee class
    public class ProductionWorker extends Employee
    {
        private int shift;
        private double payRate;
        // default constructor
        public ProductionWorker()
        {
            shift = 0;
            payRate = 0.00;
        }
        // constructor with args passed in
        public ProductionWorker(int s, double p)
        {
            shift = s;
            payRate = p;
        }
        
        // set methods for the production worker class
        public void setShift(int s)
        {
            shift = s;
        }
        public void setPayRate(double p)
        {
            payRate = p;
        }
        // get methods for the production worker calss
        public int getShift()
        {
            return shift;
        }
        public double getPayRate()
        {
            return payRate;
        }
    }

【问题讨论】:

  • 不,不,不。任何字段都不应该是公开的。使用访问器和修改器方法将它们设为私有或至多受保护
  • 您正在构建的是一个内部类,它适用一些特殊规则。一般来说,我建议为孩子创建一个新的.java 文件,这样它就不再是内部类了。如果子类声明为protected,则子类可以访问父类的字段。除此之外,我会避免使用 public 字段,而支持具有公共 getter 的私有/受保护字段。
  • 感谢您的帮助。啊,是的,为子类制作一个新文件是个好主意。然后会这样做
  • @NotX,当我为我的子类创建一个单独的 .java 文件时,我在声明子类时是否还需要使用“扩展”?
  • @Fitzgerald 比以往任何时候都多。编译器怎么会知道一个类实际上是另一个类的子类?出于多种原因,默认使用内部类是不好的风格,但避免这些不会让你省去任何写作工作。

标签: java parent-child


【解决方案1】:

制作父类的字段protected

将状态尽可能保密是一种很好的设计实践。

【讨论】:

    猜你喜欢
    • 2021-06-26
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 2017-04-13
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多