1.多态:在继承/实现情况下的一种现象,表现为对象多态(儿子,学生),行为多态(跑的快慢)
方法编译看左边,运行看右边
变量编译看左边,运行看左边
package com.itheima.多态;
public class Test {
//对象多态,行为多态
public static void main(String[] args) {
//1.对象多态
People p1=new Teacher();
p1.run();//行为多态 识别技巧:编译看左边,运行看右边
System.out.println(p1.name);
People p2=new Student();
p2.run();
System.out.println(p2.name);
}
}
class People{
public String name="父类People的名称";
public void run(){
System.out.println("人可以跑");
}
}
class Student extends People{
public String name="子类Student的名称";
@Override
public void run(){
System.out.println("跑的块");
}
}
class Teacher extends People{
public String name="子类Teacher的名称";
@Override
public void run(){
System.out.println("跑的气喘吁吁");
}
}
2.多态的好处:
package com.itheima.多态; public class Test { //多态好处 public static void main(String[] args) { //好处1:实现解耦合,右边对象可以随时切换,后续业务随即改变 People p1=new Teacher(); p1.run(); //好处2:可以使用父类类型的变量作为形参,可以接受一切子类对象 Student student=new Student(); Teacher teacher=new Teacher(); go(student); go(teacher); //p1.teach();//报错,因为编译看左边,父类没有所以报错了 } //好处2:可以使用父类类型的变量作为形参,可以接受一切子类对象 public static void go(People p){ } } class People{ public String name="父类People的名称"; public void run(){ System.out.println("人可以跑"); } } class Student extends People{ public String name="子类Student的名称"; public void test(){ System.out.println("考试"); } @Override public void run(){ System.out.println("跑的块"); } } class Teacher extends People{ public String name="子类Teacher的名称"; public void teach(){ System.out.println("教书"); } @Override public void run(){ System.out.println("跑的气喘吁吁"); } }标签:JAVA,People,void,多态,System,面向对象,public,out From: https://www.cnblogs.com/pengsuoqun123/p/18091376