15 สิงหาคม 2554

[JAVA]การเขียน Constructor และเมธอดแบบ Overload แบบฝึกหัดที่ 5.4


------------------------------------
                Main
------------------------------------

public class TestRectangle {
    public static void main(String args[]){
        Rectangle rect1 = new Rectangle();
        Rectangle rect2 = new Rectangle(10.5,8,"Red");
        rect1.setWidth(12.0);
        rect1.setHeight(5.5);
        rect1.setColor("Yellow");
        System.out.println("Rect1 : Width = "+rect1.getWidth()+", Height = "+rect1.getHeight()+", Color = "+rect1.getColor());
        System.out.println("Rect2 : Whith = "+rect2.getWidth()+", Height = "+rect2.getHeight()+", Color = "+rect2.getColor());  
        System.out.println("Area1 : "+rect1.findArea()+"\n"+"Area2 : "+rect2.findArea());
    }
}

------------------------------------
             Rectangle
------------------------------------

public class Rectangle {
    private double width =1;
    private double height = 1;
    private static String color = "white";
    public Rectangle(){
     
    }
    public Rectangle(double w,double h,String c){
        width=w;
        height=h;
        color=c;
    }
    public void setWidth(Double w){
        width=w;
    }
    public double getWidth(){
        return width;
    }
    public void setHeight(double h){
        height=h;
    }
    public double getHeight(){
        return height;
    }
    public void setColor(String c){
        color=c;
    }
    public String getColor(){
        return color;
    }
    public double findArea(){
        return width*height;
    }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น