构造方法

来源:互联网 发布:王牌特工特工学院淘宝 编辑:程序博客网 时间:2024/06/05 23:51
package t;
//构造函数
 class person1 {
 private String name;//声明姓名属性
 private int age;//声明年龄属性
 public person1(String name,int age){//定义构造函数为属性初始化
    this.setName(name);//为name属性赋值
    this.setAge(age);//为age属性赋值
    
 }
 public void tell(){//取得信息的方法
  System.out.println("姓名:"+getName()+","+"年龄"+getAge());//
 }
 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){
  this.age = age;//设置年龄并判断
 }
 }
}
public class person {
 
 public static void main(String args[]){
  person1 per = new person1("李华波",22);//调用构造方法
  per.tell();//输出信息
  
 }
 
 
}
原创粉丝点击