代码之家  ›  专栏  ›  技术社区  ›  Rishab Negi

这个关键字在抽象类中是如何工作的

  •  0
  • Rishab Negi  · 技术社区  · 6 月前

    请原谅我的代码,只关注这里的问题:

    我们知道私有字段不是继承的,当我在第2行创建对象时,对象是为Person创建的,然后当我设置 fatherName ,里面 setFatherName() 怎么样 “谁是人的对象”具有可见性设置 Test 班级私人 父亲姓名 ?

    abstract  class  Test {
        private String fatherName ;
    
        public void setFatherName(String fatherName){
            System.out.println(this.getClass().getSimpleName());
            this.fatherName=fatherName;
        }
        public String getFatherName(){
           return  fatherName;
        }
    }
    
    public class Person extends  Test{
    
        public static void main(String[] args) {
            Test person = new Person(); // #2
            person.setFatherName("Jimmy");
            System.out.println("father name is : " +person.getFatherName());
    
        }
    }
    

    输出:

    Person
    father name is : Jimmy
    

    我理解我间接用setter做这件事的背景,但如何做到 this 关键字在抽象类中起作用,因为对象是 Person 尽我所能准确地发布问题。

    1 回复  |  直到 6 月前
        1
  •  1
  •   Mario Mateaș    6 月前

    它之所以有效,是因为setter是继承的,它被标记为 public 。变量实际上也是“继承的”(这意味着它们在内存中分配了一个位置),即使它们被标记为 private 。您不能直接从子类访问它们。

    使用 公众的 方法,就像你在这里做的那样,是允许的。您调用的setter实际上是在超类内部调用的。如果你覆盖了它,你就无法访问 this.fatherName 在儿童班里。您应该将设置逻辑委托给父级。

    但使用setter应该有效。最好将你的字段标记为 protected 然而,为了尊重封装。我认为在类层次结构中,直接访问变量应该优先于 公众的 方法,而setter应用于从外部访问。