2-8编程练习
来源:2-8 编程练习
sx1011
2020-08-15 18:29:39
//测试类
public class Test {
public static void main(String[] args) {
//实例化对象,传入属性值(李明, 男,18)
Person one=new Person("李明",18,"男");
//打印输出对象信息
System.out.println(one);
System.out.println(one.toString());
}
}public class Person{
//私有属性:name(姓名)、age(年龄)、sex(性别)
private String name;
private int age;
private String sex;
//带参构造方法(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 this.name;
}
public void setAge(int age){
this.age=age;
}
public int getAge(){
return this.age;
}
public void setSex(String sex){
this.sex=sex;
}
public String getSex(){
return this.sex;
}
//重写toString方法,表示形式为:姓名:+**+ 年龄:+**+ 性别:+**
public String toString(){
return "姓名:"+this.getName()+" 年龄: "+this.getAge()+" 性别:"+this.getSex();
}
}1回答
同学你好,同学已完成练习,棒棒哒!
不过有一个小建议,建议同学创建无参构造方法,因如果定义带参构造但未定义无参构造,则带参构造会覆盖掉默认的无参构造,当使用无参构造方法创建对象时,会找不到无参构造方法报错。
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
相似问题