一、继承的目的
是为了复用代码
- 直接用继承的方法、属性
- 看不上,自己重写(方法名、参数类型和个数都一样)
二、父类
package com.extend;
public class Student {
public String name;
public int age;
public String classNo;
public String shcool;
public void toSchool(){
System.out.println("我是"+name+",我要去"+shcool+"上学!");
}
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
二、子类
package com.extend;
public class MidlleStudent extends Student{
}
package com.extend;
//继承
public class HighStudent extends Student{
//增加自己的东西
public String biology;
//重写继承的方法
public void toSchool(){
System.out.println("我是"+name+",我要去"+shcool+"上学!住宿,从宿舍到教室");
}
}
三、测试
package com.extend;
public class Test {
public static void main(String[] args) {
Student student=new Student();
student.name="吴令";
student.age=29;
student.classNo="1801";
student.shcool="guoya";
student.toSchool();
System.out.println(student.toString());
MidlleStudent ms=new MidlleStudent();
ms.toSchool();
Student hs=new HighStudent();
hs.name="高中生";
hs.age=18;
hs.classNo="1802";
hs.shcool="果芽";
hs.toSchool();
System.out.println(hs.toString());
Student ms=new MidlleStudent();
ms.toSchool();
}
}
三、java三大特性
- 封装
- 继承
- 多态
练习
- 写student类:封装(把N个属性、M个方法封装到1个java类里)
- 写MiddleStudent,继承Student类:继承(什么都不用写,就具备父类所有属性和方法)
- 写HighStudent类,继承Student类,新增字段,重写toSchool方法
- 写Test类,new MiddleStudent和new HighStudent,都用Student变量类型存储:多态(Student可以有Midlle和High多种实现类型)
向上转型

HighStudent

Student

Object
其中Object类是所有类的祖先类
java是单继承体系,一个类只能继承一个父类
HighStudent hs=new HighStudent();
能用的属性和方法=HighStudent+Student+Object
Student hs=new HighStudent();
能用的属性和方法=Student+Object
Object hs=new HighStudent();
能用的属性和方法=Object