這個題讓我更加明白了類創建對象的實質
代碼中用到:1.對象作形參;2.對象作返回值
以下用代碼具體分析:
1 class Point1{ 2 public double x; 3 public double y; 4 Point1(){} 5 6 public Point1(double x,double y){ 7 this.x=x; 8 this.y=y; 9 } 10 11 public void show(){ 12 System.out.println("x="+x+","+"y="+y); 13 } 14 15 } 16 public class Test2_2 { 17 public static void main(String args[]){ 18 19 Point1 a=new Point1(2,4); //實例化對象並完成對象的初始化 20 Point1 b=new Point1(5,7); 21 Point1 m=new Point1(); //實例化對象用於接受函數返回的對象 22 m=getMiddle(a,b); 23 m.show(); //用該對象顯示中點坐標值 24 25 } 26 27 static Point1 getMiddle(Point1 a,Point1 b){ //創建兩個對象的引用作形參.注意:此函數的返回值是一個對象 28 Point1 t=new Point1(); //實例化創建一個對象 29 t.x=(a.x+b.x)/2; 30 t.y=(a.y+b.y)/2; //橫縱坐標值相加除2即兩點間的中點 31 return t; //返回一個表示中點的對象 32 } 33 }