Discuss / Java / 多态例子

多态例子

Topic source

如果把Person的hello设为private的那么打印出来的是Person:hello,怎么解释呢?

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

Exception 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");    }
}

廖雪峰

#5 Created at ... [Delete] [Delete and Lock User]

你需要区分 getDeclaredMethod 和 getMethod 的区别

原来问题在这里,谢谢博主

因为父类的sayHello()方法是private的,子类的是public的,这种情况不是重写吧?所以不能多态。

Nonenoenen

#8 Created at ... [Delete] [Delete and Lock User]

子类不能重写父类被声明为private权限的方法

🌙

#9 Created at ... [Delete] [Delete and Lock User]

廖大一本正经的回复,这种就是不认真看教程...不过,初学者嘛~

Joker.fu_95

#10 Created at ... [Delete] [Delete and Lock User]

如果不是private,指向的还是子类的引用(多态),但是private,就没有体现出多态,而是本身的Method


  • 1

Reply