Java 构造方法

一个圆 Circle

圆心位置 x, y
半径长度 radius

请给它添加几个构造方法

package my;
public class Point
{
    public double x;  // 横坐标
    public double y;  // 纵坐标
    
    public Point()
    {
        x = y = 0;
    }
    public Point (double x, double y)
    {
        this.x = x;
        this.y = y;
    }
}
package my;

public class Circle
{
    public double x;
    public double y;
    public double radius;
    
    // 默认构造方法:初始化(0,0)的单位圆
    public Circle()
    {
        x = y = 0;
        radius = 1.0;
    }
    
    // 创建时指定圆心和半径
    public Circle(double x, double y, double radius)
    {
        this.x = x;
        this.y = y;
        this.radius =radius;
    }
    
    // 创建时指定圆心和半径 
    public Circle ( Point p, double radius)
    {
        this.x = p.x;
        this.y = p.y;
        this.radius = radius;
    }
}
ackage my;

public class HelloWorld
{
    public static void main(String[] args)
    {
        Circle c1 = new Circle();  // 默认构造方法
        Circle c2 = new Circle(1,1, 2.4); // 指定圆心和半径 
        
        Point center = new Point(1,1);
        Circle c3 = new Circle (center, 2.4); // 传Point作为参数
        
        Circle c4 = new Circle (new Point(1,1), 2.4); // 直接new一个Point作为参数        
    }
}

 

posted on 2018-11-28 10:37  Jenrry  阅读(284)  评论(0编辑  收藏  举报