Java中方法访问修饰符的继承

mav*_*vix 0 java inheritance

我正在玩继承试图完全理解它:

我已经使用私有方法创建了一个父类,并在子类中重写它并使其公开.我还为每个类重写了不同的toString方法.看起来像这样:

public class testparent {
    public String toString(){
        return ("One and two boobaloo");
    }
    private void hitMe(){
        System.out.println("BAM");
    }
}

public class testbaby extends testparent{
    public String toString() {
        return "Bananas";
    }
    public void hitMe(){
        System.out.println("BAMBAM");
    }
    public static void main(String[] args){
        testbaby testy = new testbaby();
        testparent test2 = testy;
        System.out.println(test2);
        //test2.hitMe(); //????? not allowed
        System.out.println(testy);
        testy.hitMe();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,为什么打印两个对象会产生"Bananas",但我不能同时使用这两个类的hitMe()方法?

Jac*_*ack 5

这是因为方法的动态绑定和语言本身的静态类型化.

会发生什么是Java是静态类型并且具有动态绑定,因此:

  • 该方法hitMe只能在testbaby声明的变量上调用,因为它是私有的,testparent并且由于静态类型,Java必须确保在运行时可以确定地调用该方法
  • toString可以在两个对象上调用该方法(因为它甚至从中继承Object),并且在运行时有效调用哪个方法根据运行时实例选择,而不是根据变量声明(因为动态绑定)

根据动态绑定方法,在运行时根据对象的实际实例选择方法的正确和运行时实现,而不是在声明的实例上.

这意味着,即使您声明test2为a testparent,它仍然是一个testbaby对象(因为您正在为它分配一个testbaby实例).在运行时,正确的实现将是孩子之一.

这是完全合法的,因为a testbaby a testparent.