集册 Java实例教程 用构造函数创建对象

用构造函数创建对象

欢马劈雪     最近更新时间:2020-01-02 10:19:05

514
用构造函数创建对象

public class Rectangle {
/**
时代Java公众号 - nowjava.com
**/

    public int width = 0;

    public int height = 0;

    public Point origin;


    // four constructors

    public Rectangle() {

        origin = new Point(0, 0);

    }


    public Rectangle(Point p) {

        origin = p;

    }


    public Rectangle(int w, int h) {

        origin = new Point(0, 0);
        /*
        来 自*
         n o w j a   v  a . c o m - 时  代  Java
        */

        width = w;

        height = h;

    }


    public Rectangle(Point p, int w, int h) {

        origin = p;

        width = w;

        height = h;

    }


    // a method for moving the rectangle

    public void move(int x, int y) {

        origin.x = x;

        origin.y = y;

    }


    // a method for computing the area of the rectangle

    public int getArea() {

        return width * height;

    }

}

class Point {

    public int x = 0;

    public int y = 0;


    // a constructor!

    public Point(int a, int b) {

        x = a;

        y = b;

    }

}

展开阅读全文