构造方法的重载

来源:互联网 发布:网络信息化建设 编辑:程序博客网 时间:2024/05/16 15:36
public class Person {    private String name;                //属性封装    private int age;                    //属性封装    public Person() {                   //无参构造方法    }    public Person(String name) {        //一个参数的构造方法        this.setName(name);    }    public Person(String name,int age) {//两个参数的构造方法        this.setName(name);        this.setAge(age);    }    public void setName(String name) {  //设置name属性        this.name =  name;    }    public String getName() {           //获取name属性内容        return this.name;    }    public void setAge(int age) {       //设置age属性        if(age<=0)            this.age=1;                 //默认设置1岁        else            this.age=age;    }    public int getAge() {               //获取age属性内容        return this.age;    }    public void tell() {        System.out.println("姓名:"+name+",年龄:"+age);    }    public static void main(String[] args) {        Person per = new Person();        per.setName("张三");        per.setAge(21);        per.tell();    }}

输出结果:
姓名:张三,年龄:21

原创粉丝点击