当前位置: 技术问答>java相关
我又遇到一道无法理解的题目,讲一下行吗?
来源: 互联网 发布时间:2017-04-03
本文导语: 答案是B,可是我认为最后的输出语句应该写成 System.out.println(new B().toString); 才行的啊!像题目那样写怎么会不出错呢?? 1. class A { 2. public String toString () { 3. return “4”; 4. } 5. } 6. class B extends A { ...
答案是B,可是我认为最后的输出语句应该写成
System.out.println(new B().toString); 才行的啊!像题目那样写怎么会不出错呢??
1. class A {
2. public String toString () {
3. return “4”;
4. }
5. }
6. class B extends A {
7.
8. public String toString () {
7. return super.toString() + “3”;
8. }
9. }
10. public class Test {
11. public static void main(String[] args) {
12. System.out.println(new B());
13. }
15. }
What is the result?
A. Compilation succeeds and 4 is printed.
B. Compilation succeeds and 43 is printed.
C. An error on line 9 causes compilation to fail.
D. An error on line 14 causes compilation to fail.
E. Compilation succeeds but an exception is thrown at line 9
System.out.println(new B().toString); 才行的啊!像题目那样写怎么会不出错呢??
1. class A {
2. public String toString () {
3. return “4”;
4. }
5. }
6. class B extends A {
7.
8. public String toString () {
7. return super.toString() + “3”;
8. }
9. }
10. public class Test {
11. public static void main(String[] args) {
12. System.out.println(new B());
13. }
15. }
What is the result?
A. Compilation succeeds and 4 is printed.
B. Compilation succeeds and 43 is printed.
C. An error on line 9 causes compilation to fail.
D. An error on line 14 causes compilation to fail.
E. Compilation succeeds but an exception is thrown at line 9
|
toString方法是默认的,调用new B()输出时就自动执行toString方法.
所以你说的也对,他用的也对,两种方法结果是一样的.
所以你说的也对,他用的也对,两种方法结果是一样的.
|
B
JVM自动转到toString()
JVM自动转到toString()
|
我上机验证过了,b是对的