父类是Person,属性有姓名、年龄。
子类是Student,继承了父类的属性和方法,除了父类的性别、年龄,还有自己特有的属性:成绩,有自己特有的方法:学习。
注意:子类的构造方法中,继承父类的属性,用super(属性名),并在()里传入属性类型和属性名称,即完成了父类属性的引用。子类特有的属性,则在构造方法中用this.属性名=属性名,进行引用。
Person类
public class Person { String name; int age; String sex; //含全部参数的构造方法 //右键generage,点击constructor即可 public Person(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } //无参构造方法,里面没有传参数 public Person() { } //成员方法 public void sleep() { System.out.println("休息"); } public void eat() { System.out.println("吃饭"); } }
Student类
public class Student extends Person{
//学生类特有的属性:成绩
public double score;
//无参构造方法
public Student(){
}
public Student(String name,int age,String sex,double score){
super(name,age,sex);
this.score=score;
}
//打印类
public void detail(){
System.out.println("姓名:"+name+"\t"
+"年龄"+age+"岁"+"\t"
+"性别:"+sex+"\t"
+"成绩:"+score);
}
//学生类特有的行为:学习
public void study(){
System.out.println("学生在学习");
}
}
测试类Test01
public class Test01 {
public static void main(String[] args) {
//new一个对象,调用Student类的构造方法,并赋值
Student stu = new Student("小学生李华",12,"男",100);
//调用Student类中的detail()方法,对信息进行打印
stu.detail();
stu.study();
}
}
运行结果: