如何调用被覆盖的方法的超版本? [英] How to call super-version of a method that is overridden?

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

问题描述

即使方法被重写,我也知道如何通过super.从子类中调用超类中的方法.但是如何在超类中调用该方法?

I know how to call a method in a super class from a subclass by super. even when the method is overriden. But how can I call the method in the super class?

不可能吗?

public class Test extends Super{

    public static void main (String[] args){
        Test t = new Test();
        t.print();
    }

    void print1(){
        System.out.println("Hello");
    }
}


class Super{

    void print1(){
        System.out.println("hi");
    }

    void print(){
        print1();
        // What can I do when I want to print "hi"
    }
}

推荐答案

一旦您

Once you override a function, the super-version of that function is no longer accessible, neither to the super class or the sub-class. It's called being "hidden". The only exception is calling it from within the overridden function, via super:

public class Test extends Super{
    void print1(){
        System.out.println("Hello");
        super.print1();                   //Here
    }
}
class Super{
    void print1(){
        System.out.println("hi");
    }   
}

(这正是构造函数绝对不能直接调用可能被覆盖的函数的原因.) 您还可以将Super.print1()设为私有,这意味着即使存在Test.print1(),它也不会覆盖任何内容,因为就其而言,超级版本不存在(不可见)

(This is exactly the reason that constructors must never directly call functions that are potentially overridable.) You could also make the Super.print1() private, which would mean that, even though there is a Test.print1(), it does not override anything, because, as far as it's concerned, the super-version does not exist (is not visible).

所以这个:

public class Test extends Super{
   public static void main (String[] args){
      Test t = new Test();
      t.print();
   }
   void print1(){
      System.out.println("Hello");
   }
}
class Super{
   private void print1(){
      System.out.println("hi");
   }
   void print(){
      print1();
      this.print1();
   }
}

输出以下内容:

hi
hi

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

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