java覆盖方法调用 [英] java override method invocation

查看:139
本文介绍了java覆盖方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超类:

public class SuperClass {

    public void dosomething() {
        firstMethod();
        secondMethod();
    }

    public void firstMethod() {
        System.out.println("Super first method");
    }

    public void secondMethod() {
        System.out.println("Super second method");
    }
}

子类:

public class SubClass extends SuperClass {

    public void dosomething() {
        super.dosomething();
    }

    public void firstMethod() {
        System.out.println("Sub first method");
    }

    public void secondMethod() {
        System.out.println("Sub second method");
    }
}

测试类:

public static void main(String[] args) {
      SubClass sub = new SubClass();
      sub.dosomething();
      SuperClass sup = new SuperClass();
      sup.dosomething()
}

当我运行测试方法时,我得到了这个:

when I run the test method, I got this:

Sub first method
Sub second method

你能告诉我这是怎么发生的吗?在子类 dosomething 方法中,我调用 super.dosomething(),我认为将调用super方法,但是调用了子类中的override方法。

Can you tell me how this happened? In the sub class dosomething method, I called super.dosomething() and I think the super method will be called, but the override method in sub class was called.

如果我这样做:
$
SuperClass superClass = new SuperClass( ); $
superClass.dosomething();

$


结果是:

超级第一种方法

超级第二种方法

if I do this:
SuperClass superClass = new SuperClass();
superClass.dosomething();


the result is:
Super first method
Super second method

区别在于方法调用位置。我认为必须有一些我不知道的东西:

The difference is method invocation place. I think there must be something I don`t know ):

oops!超级引用指向第一个例子中的子类......

oops!the super reference pointed to subclass in the first example...

像这样:


SuperClass sub = new SubClass();

sub.firstMethod();

sub.secondMethod();

推荐答案

调用方法的对象是SubClass类型,而不是SuperClass。即使您调用仅在SuperClass中定义的方法,您的执行上下文仍然是SubClass。因此,被覆盖的任何被调用的方法实际上都会执行重写的方法。

Your object on which the methods are invoked is of type SubClass, not SuperClass. Even if you call a method that is only defined in SuperClass, your execution context remains SubClass. So any method that is invoked that is overridden will in fact execute the overridden method.

通过将firstMethod和secondMethod声明为public,SuperClass来解决这个问题。实际上是允许子类覆盖它们的行为。如果这不合适,方法应该是私有的,或者是最终的。

The thing to take away from this is that by declaring firstMethod and secondMethod as public, SuperClass is in fact allowing subclasses to override their behaviour. If this is not appropriate, the methods should be private, or final.

这篇关于java覆盖方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆