- 定义一个人的类(属性有名字,年龄,性别。写一个能输出各个属性值的方法showInfo()),定义一个学生类(属性有学号),学生继承人类,要求:
(1)父类的属性赋值用构造方法来实现(分别用有参数构造方法和无参数构造方法实现);
(2)子类的属性也用构造方法来赋值;
(3)在子类中重写父类的showInfo()方法
(4)声明学生类的对象,调用学生的显示信息的方法。
Human类
public class Human {
protected int sex;
protected String name;
protected int age;
public Human(){
this.sex = 1;
this.name = "xiaohong";
this.age =15;
}
public Human(String name, int sex, int age) {
this.age=age;
this.setName(name);
this.sex=sex;
}
public void printinfo(){
System.out.print("name: "+this.getName()+" "+"sex: "+this.sex+" "+"age: "+this.age+" ");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Student类
public class Student extends Human{
private int id;
public Student(int id,String name,int age,int sex) {
super(name,sex,age);
// super()
this.id = id;
}
public Student(){
super();
this.id = 10;
}
public void printinfo(){
super.printinfo();
System.out.println("id: "+this.id);
}
public static void main(String[] args) {
int id = 12;
int age = 15;
int sex = 0;
String name ="w";
Student s1 = new Student(id, name, age, sex);
Student s2 = new Student();
s1.printinfo();
s2.printinfo();
}
}