当前位置: 代码迷 >> 综合 >> Java 要用子类的新方法就不要发生多态
  详细解决方案

Java 要用子类的新方法就不要发生多态

热度:48   发布时间:2024-02-02 05:44:27.0

举例: 


public class TestDuoTai {public static void main(String[] args) {People people = new Student();people.say();//people.say2();//会报错:The method say2() is undefined for the type PeopleSystem.out.println("-----");Student s = new Student();s.say();s.say2();}}abstract class People{abstract void say();
}class Student extends People{@Overridevoid say() {System.out.println("我是人");}void say2() {System.out.println("我是学生");}
}

输出结果:

我是人
-----
我是人
我是学生

当子类继承父类的时候,如果子类有新的方法并且要使用,不要发生多态,否则就只能用父类的方法,子类的新方法没法用。