代码演示:
首先创建类:
public class People { //人类
public String name = "people";
public void run(){ //跑步
System.out.println("人会跑步");
}
}
public class Student extends People{ //学生类,继承人类
public String name = "student";
@Override
public void run() { //跑步
System.out.println("学生跑的贼快~");
}
}
public class Teacher extends People{ //老师类,继承人类
public String name = "teacher";
@Override
public void run() { //跑步
System.out.println("老师跑的气喘吁吁~");
}
}
Test:
public class Test {
public static void main(String[] args) {
People s = new Student(); //对象多态,人可以是学生,人的范围比学生大,学生继承自人,学生也是人
s.run(); //学生跑步
People t = new Teacher(); //同理学生
t.run(); //老师跑步
}
}
运行结果:
?
举例:
仍然是刚才的人类、学生类、老师类?,输出他们的name:
public class Test2 {
public static void main(String[] args) {
People s = new Student();
System.out.println(s.name); //编译看左边,运行看左边
People t = new Teacher();
System.out.println(t.name);
}
}
结果:
?
示例:
示例:
?
?