标准的类的写法

/*
    一个标准类的3.0版本写法:
        类:
            成员变量:使用private关键字进行修饰
            构造方法:提供一个无参构造方法,以及一个有参构造方法
            成员方法:getXxx()和setXxx()
            show():展示成员变量值的情况
 */
class Phone2 {
    private String brand;
    private String color;
    private int price;

    public Phone2() {
    }

    public Phone2(String brand, String color, int price) {
        this.brand = brand;
        this.color = color;
        this.price = price;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public void show() {
        System.out.println("品牌:" + this.brand + ", 颜色:" + this.color + ", 价格:" + this.price);
    }
}

public class ConstructorDemo3 {
    public static void main(String[] args) {
        // 先使用无参构造方法把对象创建出来,然后使用setXxx()对成员变量进行赋值。
        Phone2 p1 = new Phone2();
        p1.setBrand("小米6");
        p1.setColor("陶瓷黑");
        p1.setPrice(5999);
        p1.show();

        //直接调用有参的构造方法创建对象,在创建对象的同时给成员变量赋值。
        Phone2 p2 = new Phone2("华为mate60", "白色", 6999);
        p2.show();
    }
}
posted @ 2024-08-01 21:46  ていせい  阅读(3)  评论(0编辑  收藏  举报