构造器

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age<0||age>150){
            System.out.println("年龄不合法");
        }
        this.age = age;
    }
    public void talk(){
        System.out.println(name+","+age+"岁会说话");
    }
    //空参构造函数
    public Person(){

    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
class PersonDemo{
    public static void main(String[] args) {
        Person p=new Person("张三",20);
        //p.setName("张三");
        //p.setAge(20);
        p.talk();
    }
}

  构造器的参数传递图解:

posted @ 2019-03-18 20:29  T&K  阅读(145)  评论(0编辑  收藏  举报