1. class Point 
2. {
3.  protected int x,y;
4. public Point(int a,int b)
5. {
6. x=a;
7. y=b;
8. System.out.println("Point constructor: "+this.f());//到这不理解
9.
10. }
11. public String f()
12. {
13. return "["+x+","+y+"]";
14. }
15. }
16. class Circle extends Point
17.  {
18. protected double radius;
19. public Circle()
20. {
21. super(4,5);
22. radius=10;
23. System.out.println("Circle constructor: "+this.f());
24. }
25. public String f()
26. {
27. return "Center= "+super.f()+"Radius="+radius;
28. }
29. } 以上程序结果为何是:
Point constructor:Center=[4,5]Radius=0.0
Circle constructor:Center=[4,5]Radius=10.0而不是:
Point constructor:[4,5]
Circle constructor:Center=[4,5]Radius=10.0
呢????
程序执行到第8行时为何不是接着执行第11行的f()函数而是直接跳到第25行的f()函数呢?
上面第8行不是有this.f()限制是本类中的第11行的f()方法吗?为何却执行子类第25行的f()方法?多态性也不至于这样的执行吧?不解,请大虾帮忙!谢

解决方案 »

  1.   

    1. class Point 
    2. {
    3.  protected int x,y;
    4. public Point(int a,int b)
    5. {
    6. x=a;
    7. y=b;
    8. System.out.println("Point constructor: "+this.f());//到这不理解
    9.
    10. }
    11. public String f()
    12. {
    13. return "["+x+","+y+"]";
    14. }
    15. }
    16. class Circle extends Point
    17.  {
    18. protected double radius;
    19. public Circle()
    20. {
    21. super(4,5);
    22. radius=10;
    23. System.out.println("Circle constructor: "+this.f());
    24. }
    25. public String f()
    26. {
    27. return "Center= "+super.f()+"Radius="+radius;
    28. }
    29. } 
    30. public class Test1
    31. {
    32. public static void main(String[] args) 
    33. {
    34. Circle c=new Circle();
    35. }
    36. };以上程序结果为何是:
    Point constructor:Center=[4,5]Radius=0.0
    Circle constructor:Center=[4,5]Radius=10.0而不是:
    Point constructor:[4,5]
    Circle constructor:Center=[4,5]Radius=10.0
    呢????
    程序执行到第8行时为何不是接着执行第11行的f()函数而是直接跳到第25行的f()函数呢?
    上面第8行不是有this.f()限制是本类中的第11行的f()方法吗?为何却执行子类第25行的f()方法?多态性也不至于这样的执行吧?不解,请大虾帮忙!谢
      

  2.   

    生成的是子类:Circle c=new Circle(),即便构造函数中调用父类,但是它的this仍然是指向自身的.所以调用的还是Circle的f()方法