当你执行A thing = new B()时,实例变量调用如何工作;其中B是A的子类? [英] How does instance variable invocation work when you do A thing = new B(); where B is a subclass of A?

查看:81
本文介绍了当你执行A thing = new B()时,实例变量调用如何工作;其中B是A的子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能在某处得到了回答,但我不知道该搜索什么。想象一下,你有以下......

This is probably answered somewhere, but I have no idea what to search for. Imagine you have the following...

超类,Animal.java

The superclass, Animal.java

public class Animal {
  public String noise = "squeak";
  public String toString() { return noise; }
}

子类Lion.java

The subclass, Lion.java

public class Lion extends Animal {
  public String noise = "ROAR!!";
  public String toString() { return noise; }
}

主类Runner.java

The main class, Runner.java

public class Runner {
  public static void main(String[] args) {
    Animal a = new Animal();
    System.out.println(a);
    System.out.println(a.noise);
    Lion b = new Lion();
    System.out.println(b);
    System.out.println(b.noise);
    Animal c = new Lion();
    System.out.println(c);
    System.out.println(c.noise);
  }
}

输出为:

squeak
squeak
ROAR!!
ROAR!!
ROAR!!
squeak

为什么c.noise会返回吱吱声?实例方法调用和实例变量之间有什么区别,一个返回你期望的,另一个不返回?为什么Java会这样做?

Why does c.noise return squeak? What is the difference between instance method invocation and instance variables that one returns what you'd expect, and the other does not? Why does Java do this?

谢谢

推荐答案

简答:

您可以覆盖方法,但不能覆盖字段。

You can override methods, but it's not possible to override fields.

长答案:

每个类都会看到它自己的方法和字段以及它的父节点(私有方法除外)。如果子进程delcare一个名称相同的方法,作为其父类中方法的名称,则此方法变为重写 - 如果在子实例上以某种方式调用此方法(即使从父母的一种方法),将使用全新的方法而不是父方法。孩子仍然可以通过 super.method(...)来调用他最后一位父母的原始方法。

Each class sees the methods and fields of it's own and of it's parents (except for private methods). If the child delcares a method, whose name is the same, as the name of the method in his parent class, this method becomes overridden - if this method is somehow invoked on the child instance (even from the one of the parent's methods), the brand new method will be used instead of the parent's one. Child may still call the original method of his last parent via super.method(...) call.

但是当我们来到田野时,故事就不同了。如果子元素声明了一个新字段,它的名称与父类中的字段完全相同,它只是隐藏父字段而不覆盖,就像本地变量隐藏全局字段一样。因此,子方法只会看到孩子的字段,但父母的方法将继续看到父母的字段,并且父母的任何方式都不会看到孩子的字段 - 这就是你所拥有的。

But the story is different when we come to the fields. If the child declares a new field, that is named exactly as the field in parent class, it will simply hide the parent's field without overriding, just like the local variable hides global one. So the child methods will simply see the child's fields, but the parent's method will continue to see parent's field, and child's field will not be visible by any means from the parent class - that's what you've got.

孩子可以通过((父)这个)访问它的父母的字段.field

这篇关于当你执行A thing = new B()时,实例变量调用如何工作;其中B是A的子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆