有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我不理解“this”与超类一起使用

我有两个类和一个接口,如下所示。 快速总结:接口Winterface、大类、扩展大类并实现Winterface的小类

public interface Winterface {}


public class Big {

    public int hello = 88;

    public Big() {}

    public void theMethod() {
        System.out.println ("Big was here: " + (this instanceof Winterface) + ", " + this.hello);
    }
}

public class Little extends Big implements Winterface{

    private boolean hello = true;
    public Little(){}

    public void theMethod() {
        super.theMethod();
        System.out.println("Little was here: " + hello);
    }

    public static void main(String [] args) {
        Little l = new Little();
        l.theMethod();
    }
}

当我执行main时,我得到以下输出

Big在这里:没错,88 这里没有什么:真的

我的问题是,你怎么能

1)(此Winterface实例)返回true,但

2)这个。你好,88岁吗? 如果是这样的话。hello=88,然后this=Big,这不是Winterface的实例

我不明白这怎么可能,提前谢谢

编辑:谢谢大家,我现在明白了“this”指的是little,它是一个大而复杂的词。因为该方法被称为super。method(),可用变量“hello”是Big中的变量,尽管“this”指的是little


共 (5) 个答案

  1. # 1 楼答案

    lLittle,但是LittleBig并且也实现了Winterface的行为
    super是对父类的调用,因此使用父类的hello成员(即Big
    您所做的不是this.hello,而是super.theMethod()使用父级的类成员变量hello

    更新:
    super.theMethod()调用父类中相应的方法。在父类中,您可以访问父类的字段(也属于派生类,因为Little也是Big)。因此,此时的this.hello正在访问属于父类的代码部分
    您可以想象Little的内存打印如下:

    ++++++++
    + Big  +
    --------
    +Little+
    ++++++++  
    

    因此Little具有父级的所有成员变量,即Big,当代码在super.theMethod()内运行时,它在Big的“代码区”内运行
    正如彼得在他的回答中所说的那样,方法不支持多摩门教,我希望这种过于简单化的描述有助于理解这一点

  2. # 2 楼答案

    this只能是一个类。但是this.hello是该类可以访问的字段

    因为this只能是一个类,所以它是一个Little,它有一个父Big,当你在其父中调用一个只能看到hello的方法时,它实现了Winterface

    也就是说,Java支持方法的多态性,但不支持字段

  3. # 3 楼答案

    这里发生的事情是,当您在{}中定义变量{}时,您没有覆盖{}中的变量{},而是在{}中定义一个新变量{},该变量在{}中隐藏变量{}。因此,在Big的范围内,hello将指88的整数值,在Little的范围内,hello将指true。这些变量都包含在对象中,唯一的区别是引用它们的范围

    正如其他人所说,instanceof是一个比较对象的运行时类型(由this.getClass()返回的内容)的操作符。在Big中时,即使对象中的变量范围将引用Bigthis仍然是运行时类型Little,这就是为什么它是Winterface的实例

  4. # 4 楼答案

    这是因为this instanceof ...检查不使用静态(即编译时)类型(即Big),而是使用对象的(this)动态运行时类型(即this.getClass()),在您的示例中是Little。如果它使用静态类型,那么操作符将毫无意义,因为我们会:

    Object obj = "foo";
    
    if (obj instanceof Object) { /* always entered */ }
    /* but */ if (obj instanceof String) { /* never entered */ }
    

    静态地,在编译时。instanceof运算符的目的是启用运行时类型测试,例如:

    Object obj = /* whatever */;
    
    if (obj instanceof String) {
    
        String str = (String)obj;   // Cast cannot fail
        ...
    
    } else if (obj instanceof Long) {
    
        Long val = (Long)obj;       // Cast cannot fail
        ...
    }
    

    请注意,此技术只能少量使用

  5. # 5 楼答案

    你的变量是大和小的实例。这是Little的直接实例,但由于Little继承自Big,因此instanceof操作符也将为Big返回true

    Little l = new Little();
    System.out.println(l instanceof Little); // true, l is an instance Little
    System.out.println(l instanceof Big); // true, l is an instance of Little which inherits from Big
    

    你的另一个误解(我假设)是“方法查找”是如何工作的。当您调用该方法时,它会选择Little对该方法的实现。当你叫super的时候。不过,在该方法中,您明确地说了“调用Big的此方法版本”,然后在该方法中使用Big的hello变量,而不是Little的hello变量