简体   繁体   English

Java在父母和孩子这不能按预期工作

[英]Java this in parent and child not working as expected

I'm misunderstanding something really basic with inheritance. 我误解了继承的一些基本知识。 I have a parent class: 我有一个家长班:

public class Parent {
    String s = "Parent";
    Parent () {}
    String getS() {
        return this.s;
    }
}

and a child class: 和一个孩子班:

public class Child extends Parent {
    String s = "Child";
    Child() { }
}

Main is like: 主要是这样的:

Parent parent = new Parent();
Child child = new Child();
Log.e(TAG, "parent:" + parent.getS());
Log.e(TAG, "child:" + child.getS());

I expect parent.getS() to return "Parent" and child.getS() to return "Child" but both return "Parent." 我希望parent.getS()返回“ Parent”,而child.getS()返回“ Child”,但都返回“ Parent”。 Doesn't the method prefix determine the this for the method when called this way? 没有方法前缀决定this的方法叫这样的时候?

Thank you Steve S. 谢谢史蒂夫·S。

  • Your getS() methods from parent class is inherited in Child class and hence it is available for Child object. 父类的getS()方法是在Child类中继承的,因此可用于Child对象。
  • Overriding is only for methods and not for instance variables. 覆盖仅适用于方法,不适用于实例变量。
  • So even if you define a new variable with same name, it will not take effect as it will not be overridden 因此,即使您定义了一个具有相同名称的新变量,它也不会被覆盖而不会生效。

You should create a getter method ie getS() in the Child class to retrieve "Child" when you call child.getS() in your main method. 您应该在Child类中创建一个getter方法,即getS(),以便在您的main方法中调用child.getS()时检索“ Child”。 In this way, you override the getS() method that was inherited from the Parent class. 这样,您将覆盖从Parent类继承的getS()方法。

The way you would set the s -member in the parent-portion of a child-class, would be to offer a protected constructor (it could, of course, also be public ): 在子类的父部分中设置s -member的方法是提供一个protected构造函数(当然,它也可以是public ):

protected Parent(String s) { this.s = s; }

which sets the string to the given value. 将字符串设置为给定值。 You would then call this constructor as the first call in your child-constructor with 然后,您将把此构造函数称为子构造函数中的第一个调用,

super("Whatever you want");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM