Java面向对象-类与对象-构造器

1)    构造器的声明

构造器名称必须和类名保持一致!

一个类可以有多个构造器,但是这些构造器的参数列表必须不同!

构造器包括 无参构造器和有参构造器;当没有定义有参构造器时,系统会默认创建无参构造器。

public class Mobile {
    public String brand;
    public String type;
    public int weight;

    // 构造器,必须与类名保持一致
    public  Mobile (String brand,String tp,int wt){
        brand = brand;
        type = tp;
        weight = wt;
        System.out.println("有參构造器");
    }
    //    无参构造器
    public Mobile() {
        System.out.println("无參构造器");
    }

    public String getBrand() {
        return brand;
    }

    public String getType() {
        return type;
    }
    public int getWeight(){
        return weight;
    }

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

    public void setType(String type) {
        this.type = type;
    }
    public void setWeight(int W){
        this.weight=W;
    }


    public static void main(String[] args){
        Mobile apple;
        //调用有参构造器
        apple = new Mobile("apple","ios",200) ;
        //调用无参构造器
        Mobile apple1 = new Mobile();

        System.out.println(apple.weight);
        apple.setWeight(82);
        System.out.println(apple.weight);
        apple.weight=23;
        System.out.println(apple.weight);

//        System.out.println(JSON.);
    }

}

 

posted on 2021-06-30 17:50  cStream  阅读(47)  评论(0)    收藏  举报