练习打卡~请老师检查~
来源:2-8 编程练习
Heijyu
2020-05-23 23:40:07
package hierarchyExercise2_8; public class Person { //私有属性:name(姓名)、age(年龄)、sex(性别) private String name; private int age; private String sex; //无参构造方法 public Person() { this(null,0,null); } // 带参构造方法(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() { String str = "姓名:" + this.getName() + " 年龄:" + this.getAge() + " 性别:" + this.getSex(); return str; } } package hierarchyExercise2_8; import hierarchyExercise2_8.Person; public class Test { public static void main(String[] args) { //实例化对象,传入属性值(李明, 男,18) Person person = new Person("李明",18,"男"); //打印输出对象信息 System.out.println(person); System.out.println(person.toString()); } }
1回答
同学你好,测试同学的代码是正确的,很不错呢,但还有如下一个问题:
1、包名所有字母均小写如:hierarchyExercise2_8应改为hierarchyexercise2_8
祝学习愉快~
相似问题