【问题标题】:What is the output if subclasss does not override to string overrided by superclass?什么是子类的输出不覆盖被超类覆盖的tostring?
【发布时间】:2013-08-16 14:22:59
【问题描述】:

In which of the following case i get output "Hello World" ?

class A{

@Override
public String toString() {
    return "Hello World";
}

}

public class B extends A{

public void print(){
        //replace code that displays "Hello World"
    }

    public static void main(String args[]){
        new B().print();
    }

}

我。 System.out.println(new A());

二。 System.out.println(new B());

III.System.out.println(this);

1. only I
2. I and III
3. I and II
4. all I,II and III

它的answer is 4all I,II and III

i understood about I but why II and III is also right ?

EDIT : Also specify which section of jls provides this specification ?

【问题讨论】:

  • toString() 被所有子类覆盖。
  • 但这里为什么在创建子类实例的情况下打印输出到超类的字符串
  • 在下面查看我的答案。

标签: java tostring overriding


【解决方案1】:

B 类是 A 类的扩展,因此 B 继承 A 拥有的所有方法(即 B 的 toString() 也将返回“Hello World”)。这就是为什么当您在 B 类对象(即 this 和 new B())上调用 print() 时,它会说“Hello World”。

如果您希望它返回不同的字符串,则必须再次重新定义/覆盖 B 类中的 toString() 函数。

【讨论】:

    【解决方案2】:

    如果你引用类中的一个方法,它会在同一个类中搜索,如果没有找到,则在超类中搜索,依此类推,直到你到达Object 类。

    无论何时你执行System.out.println(object),它总是会调用对象的toString() 方法。如果不实现,则调用超类toString()

    • 对于System.out.println(new B());,它的超类AtoString() 被称为B 并没有覆盖它。

    • 对于System.out.println(this);;因为this 指的是类B 的对象,同样toString() 的超类A 被称为B 并没有覆盖它。

    【讨论】:

    • 谢谢桑托什。但是你知道 jls 的哪个部分为此提供了理由。
    • specific section in JLS 没有明确提及这一点。但这是继承的自然含义。 This link 提供了一些信息。
    【解决方案3】:
    • System.out.println(new A());

      创建了 A 的新对象,并且默认情况下直接打印对象时会调用 toString() 方法。

    • System.out.println(new B());

      创建了 B 的新对象。现在您将一个对象作为参数传递给 println()。因此默认情况下再次调用 toString()。但是由于您尚未在类中定义 toString() B.所以会调用A类的toString()

    • System.out.println(this);

      这与第二种情况相同。

    p.s 为了更好地理解将 B 类中的 print() 方法更改为 toString()。然后你就可以看出区别了。

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 2012-09-15
      • 1970-01-01
      • 2023-04-02
      • 2020-10-21
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      相关资源
      最近更新 更多