Java 建立多重定義的建構方法

markdown #說明 這個是一種彈性的建構方法,鈄過這樣的方式就可以方便呼叫,不需要再個別處理變數以及宣告。 #操作流程 ##Code ``` package overload; class Point { public int x,y; public Point(int x, int y) { this.x=x; this.y=y; } } class Rectangle { Point upperleft; Point lowerright; //full create method public Rectangle (Point upperleft,Point lowerright) { this.upperleft=upperleft; this.lowerright=lowerright; } //don't need argv public Rectangle() { this(new Point(0,0),new Point(5,-5)); } // public Rectangle(int x1,int y1, int x2 ,int y2) { this(new Point(x1,y1 ),new Point(x2,y2)); } //square public Rectangle(Point upperleft, int length) { this(upperleft, new Point(upperleft.x+length, upperleft.y -length)); } //caculate public int area() { return (lowerright.x-upperleft.x)*(upperleft.y - lowerright.y); } } public class constructor { public static void main(String[] argv) { Rectangle a =new Rectangle (0,0,5,-5); Rectangle b =new Rectangle(new Point (3,3),4); System.out.println("a's area is :" +a.area()); System.out.println("b's area is :" +b.area()); } } ``` ##DEMO

留言