Topic: 关于super

  Print this page

1.关于super Copy to clipboard
Posted by: caoguanghui
Posted on: 2006-10-13 22:38

public class PrintClass {
int x = 0;
int y = 1;

void printMe() {
System.out.println("x is " + x + ", y is " + y);
System.out.println("I am an instance of the class " +
super.getClass().getName());
}
}

class PrintSubClass extends PrintClass {
int z = 3;

public static void main(String[] arguments) {
PrintSubClass obj = new PrintSubClass();
obj.printMe();
}
}
****************************************************************
javac PrintClass.java后
执行: java PrintSubClass
为什么输出结果是 I am an instance of the class PrintSubClass
而不是 I am an instance of the class PrintClass ?

2.Re:关于super [Re: caoguanghui] Copy to clipboard
Posted by: jigsaw
Posted on: 2006-10-15 05:35

super.getClass().getName()

最终call到的是Object的getClass() 方法

而这个方法返回的是当前class的instance

所以返回的是PrintSubClass

我们换个例子看 这次我们看toString()


public class A {
public String toString() {
return "i am A";
}
}

class B extends A {
void p() {
System.out.println(super.toString());
}

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

class C extends B {

public static void main(String[] args) {
new C().p();
}
}


你分别运行一下
java B

java C

看看是不是懂了

3.Re:关于super [Re: caoguanghui] Copy to clipboard
Posted by: caoguanghui
Posted on: 2006-10-16 17:17

谢谢 我去理解一下

4.Re:关于super [Re: caoguanghui] Copy to clipboard
Posted by: caoguanghui
Posted on: 2006-10-16 18:24

对不起哦,我还是不明白.我太笨了.能不能再详细一点啊?我把程序改成这样了:
***********************************************************
public class A {
public String toString() {
   return super.getClass().getName();
  }
}
class B extends A {
void p() {
   System.out.println(toString());
}
public static void main(String[] args) {
  new B().p(); }
  }
class C extends B {
public static void main(String[] args) {
    new C().p();
  }
     }
***********************************************************
编译后运行结果:


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923