各位前辈,本人刚接触JAVA,感觉真难啊,看到了《Java 2从入门到精通》的第5章,对上面的例题有点迷惑,能否帮助分析一下运行的流程,十分的感谢!
import java.io.PrintWriter;
public class PointTest {
  public static void main (String args[]){
    PrintWriter out = new PrintWriter(System.out,true);
    MyPoint mp = new MyPoint(4,3);
    Point2D p = new Point2D(11);
    Point2D q = mp;
    mp.x = 5;mp.y = 12;
    out.println("\n\tDataMember Access Test:\n");
    out.println("mp = (" + mp.x + :,"+ mp.y + ")");
    out.println("p = (" + p.x + :,"+ p.y + ")");
    out.println("q = (" + q.x + :,"+ q.y + ")");
    out.println("\n\tCastingTest:\n");
    out.println("(Point2D)mp = (" + ((Point2D)mp).x + "," + ((Point2D)mp).y + ")");
    out.println("(MyPoint)q = (" + ((MyPoint)q).x + "," + ((MyPoint)q).y + ")");
    out.println("\n\tMethodMember Access Test\n:");
    out.println("mp.length() = "+ mp.length());
    out.println("p.length() = "+ p.length());
    out.println("q.length() = "+ q.length());
    out.println("mp.distance() = "+ mp.distance());
    out.println("\n\tCasting Test:\n");
    out.pirntln("((Ponit2D)mp.length() = " + ((Point2D)mp.length());
    out.pirntln("((Ponit2D)q.length() = " + ((Point2D)q.length());
    out.pirntln("((MyPoint)q.distance() = " + ((MyPoint)q.distance());
  }
}public class Point2D {
  int x,y;
  Point2D() {
    this (0,0);
  }
  Point2D (int x) {
    this (x,0);
  }
  Point2D (int x,int y) {
    this.x = x;
    this.y = y;
  }
  double length() {
    return Math.sqrt(x * x + y * y);
  }
}
public class MyPoint extends point2D {
  int x,y;
  MyPoint (int x,int y) {
    super (x,y);
    this.x=y;
    this.y=y;
  }
  double length (){
    return math.sqrt (x * x + y * y);
  }
  double distance (){
    return Math.abs (length () - super.length ());
  }
}结果:
C\MasteringJava\CH05:>java PointTest
Data member Access Test:
mp = (5,12)
p = (11,0)
q = (4,3)        Casting Test:(Point2D)mp = (4,3)
(MyPoint)q = (5,12) Method Member Access Test:
mp.length() = 13.0
p.length() = 11.0
q.length() = 13.0
mp.distance() = 8.0 Casting Test:
((Point2D) mp).length() = 13.0
((Point2D) q).length() = 13.0
((MyPoint)q).length() = 8.0

解决方案 »

  1.   

    mp = (5,12) 
    p = (11,0) 
    q = (4,3) lz是不懂为什么会q=(4,3)而不是(5,12)吗?
    在MyPoint下也定义了x,y,所以当调用mp.x=5,mp.y=12后,父类定义的x和y是没有改变的。因此转型为(Point2D)时,由于Point2D的引用只能引用它自己定义的变量,所以读到的是(4,3)。
    而MyPoint下有4个成员变量,自己的x和y,还有父类的x和y(在类外不能直接访问)。ps:在MyPoint的constructor中应该是this.x=x吧?
      

  2.   

    代码一多我就头晕 尤其是很多行都是一样的开头out.pirntln。
      

  3.   

    Casting Test: (Point2D)mp = (4,3) 
    (MyPoint)q = (5,12) 

    Method Member Access Test: 
    mp.length() = 13.0 
    p.length() = 11.0 
    q.length() = 13.0 
    mp.distance() = 8.0 

    Casting Test: 
    ((Point2D) mp).length() = 13.0 
    ((Point2D) q).length() = 13.0 
    ((MyPoint)q).length() = 8.0
    这些值怎么调用的更是糊涂啦,再次谢谢啦,让我拨开乌云见明月吧!