多态例子
Topic sourceException in thread "main" java.lang.NoSuchMethodException: Person.hello()
编译不过的情况下,你运行的是旧的class
您运行一下这段代码,我的环境jdk1.8.0_181能通过编译
public class Main { public static void main(String[] args) throws Exception{ MyPerson std = new MyStudent(); Method m = MyPerson.class.getDeclaredMethod("sayHello"); m.setAccessible(true); m.invoke(std); }}class MyPerson { private void sayHello() { System.out.println("Person:hello"); }}class MyStudent extends MyPerson { public void sayHello() { System.out.println("Student:hello"); }}
public class Main {
public static void main(String[] args) throws Exception{
MyPerson std = new MyStudent(); Method m = MyPerson.class.getDeclaredMethod("sayHello"); m.setAccessible(true); m.invoke(std); }
}
class MyPerson {
private void sayHello() {
System.out.println("Person:hello"); }
}
class MyStudent extends MyPerson {
public void sayHello() {
System.out.println("Student:hello"); }
}
- 1
如雨随形space
如果把Person的hello设为private的那么打印出来的是Person:hello,怎么解释呢?