toString()函数是每个Java类都有的,即使你没有定义,系统也默认给你写一个。 这个函数的作用是给出这个类的描述信息(在直接打印类时调用),系统自带的toString()会打印“类名@内存地址”,举个例子:/*A没有定义toString,系统自带*/ class A { int a; public A() { a = 10; } }/*B实现了toString,调用时用这个了*/ public class B { int b; public B() { b = 11; } public String toString() { String msg = "Class B: " + b; return msg; } public static void main(String[] args) { A a = new A(); B b = new B();
System.out.println(a); System.out.println(b); } }
你现在rebuild一下这3个类文件,应该会编译不通过的。
class A { int a; public A() { a = 10; } }/*B实现了toString,调用时用这个了*/ public class B { int b; public B() { b = 11; } public String toString() { String msg = "Class B: " + b; return msg; } public static void main(String[] args) { A a = new A(); B b = new B();
System.out.println(a); System.out.println(b); } } ------------------------------------------------------------------------这题输出A@126b249 Class B:11这并没能说明什么问题。A继承自Object,A中并没有定义toString(), A a = new A(); System.out.println(a); 这当然会调用Object类的toString() B中定义了toString(), B b = new B(); System.out.println(b); 这当然会调用B的toString() -------------------------------------------------------但这些对我所问的问题有何联系呢?请指教再声明,我就对没有绕编译
虚了呢????
高手解答
在fun版本中,test对象没有指向fun()方法的指针区域。
这个函数的作用是给出这个类的描述信息(在直接打印类时调用),系统自带的toString()会打印“类名@内存地址”,举个例子:/*A没有定义toString,系统自带*/
class A {
int a;
public A() {
a = 10;
}
}/*B实现了toString,调用时用这个了*/
public class B {
int b;
public B() {
b = 11;
}
public String toString() {
String msg = "Class B: " + b;
return msg;
} public static void main(String[] args) {
A a = new A();
B b = new B();
System.out.println(a);
System.out.println(b);
}
}
int a;
public A() {
a = 10;
}
}/*B实现了toString,调用时用这个了*/
public class B {
int b;
public B() {
b = 11;
}
public String toString() {
String msg = "Class B: " + b;
return msg;
} public static void main(String[] args) {
A a = new A();
B b = new B();
System.out.println(a);
System.out.println(b);
}
}
------------------------------------------------------------------------这题输出A@126b249
Class B:11这并没能说明什么问题。A继承自Object,A中并没有定义toString(),
A a = new A();
System.out.println(a);
这当然会调用Object类的toString()
B中定义了toString(),
B b = new B();
System.out.println(b);
这当然会调用B的toString()
-------------------------------------------------------但这些对我所问的问题有何联系呢?请指教再声明,我就对没有绕编译
wdong18(东东) :因为在内存中,test对象拥有指向toString()方法的指针,而这个指针被赋值指向了test1()的toString()方法。
在fun版本中,test对象没有指向fun()方法的指针区域。-------------------------------多谢,我彻底明白了。原来是继承链的关系
却没fun()方法 :)