练习打卡,请老师检查
来源:2-8 编程练习
慕前端2370429
2020-05-26 00:16:52
public class Person{
//私有属性:name(姓名)、age(年龄)、sex(性别)
private String name,sex;
private int age;
//带参构造方法(name、age、sex为参数)
public Person(String name,int age,String sex){
this.setName(name);
this.setAge(age);
this.setSex(sex);
}
//通过封装实现对属性的get/set方法设定
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setAge(int age){
if(age<=0||age>100)
this.age=18;
else
this.age=age;
}
public int getAge(){
return age;
}
public void setSex(String sex){
if(sex.equals("男")||sex.equals("女"))
this.sex=sex;
else
this.sex="男";
}
public String getSex(){
return sex;
}
//重写toString方法,表示形式为:姓名:+**+ 年龄:+**+ 性别:+**
public String toString(){
String info="姓名:"+this.getName()+" 年龄:"+this.getAge()+" 性别:"+this.getSex();
return info;
}
}
====================================
//测试类
public class Test {
public static void main(String[] args) {
//实例化对象,传入属性值(李明, 男,18)
Person one=new Person("李明",18,"男");
//打印输出对象信息
System.out.println(one.toString());
System.out.println(one);
}
}
1回答
好帮手慕阿满
2020-05-26
同学的代码完成的不错,继续加油。
祝:学习愉快~
相似问题