集册 Java实例教程 调用构造函数

调用构造函数

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

481
这叫构造函数

class Point {

    public int x = 0;
    /* from 
    N o w J a v a . c o m - 时代Java*/

    public int y = 0;


    // a constructor!

    public Point(int x, int y) {

        this.x = x;

        this.y = y;

    }

}

class Rectangle {

    public int width = 0;

    public int height = 0;

    public Point origin;/** from nowjava.com - 时代Java**/


    // four constructors

    public Rectangle() {

        origin = new Point(0, 0);

    }


    public Rectangle(Point p) {

        origin = p;

    }


    public Rectangle(int w, int h) {

        this(new Point(0, 0), w, 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 area() {

        return width * height;

    }

}

public class SomethingIsRight {

    public static void main(String[] args) {

        Rectangle myRect = new Rectangle();

        myRect.width = 40;

        myRect.height = 50;

        System.out.println("myRect's area is " + myRect.area());

    }

}

展开阅读全文