85 构造方法 空参和带参

发布时间 2023-06-13 15:41:34作者: 胖豆芽

对象

package com.fqs.demo061302;

public class Girl {
    //属性
    //成员变量
    private String name;

    private int age;

    /*public  void setAge(int age) {//【局部变量 】 名称可以和上面的【成员变量】一样
        //赋值
        if(age<50 &&age>18){
            this.age=age;//将方法里的【局部变量】赋值给 【成员变量】
            System.out.println("合法");
        }else {
            System.out.println("不合法");
        }

    }

    public  int getAge () {
        //获取值
        return age;

    }*/
    public Girl() {
        //空参构造
    }
    public Girl(String name,int age){
        //带参构造
        this.age=age;
        this.name=name;
    }
    public void setAge(int age){
        if(age>18&&age<50){
            this.age=age;
        }else {
            System.out.println("不合法");
        }

    }
    public int getAge(){
        return age;
    }

    public void setName(String name){
        this.name=name;
    }
    public String getName(){
        return name;
    }

    public  void shop() {
        System.out.println("购物");

    }
    public  void play() {
        System.out.println("玩游戏");

    }

    //方法
}

方法调用

package com.fqs.demo061302;

public class GirTest {
    public static void main(String[] args) {
        Girl g1=new Girl("doudou",19);


        System.out.println("女朋友:"+g1.getName()+" "+g1.getAge());
    }
}