可以在子类中重写超类中的私有方法吗? [英] Can a private method in super class be overridden in the sub-class?

查看:288
本文介绍了可以在子类中重写超类中的私有方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在Java中覆盖私有方法吗?
如果不是,那么以下代码如何工作?

Can private methods be overridden in Java? If no, then how does the following code work?

class Base{
      private void func(){
            System.out.println("In Base Class func method !!");         
      };
}

class Derived extends Base{
      public void func(){   //  Is this a Method Overriding..????        
            System.out.println("In Derived Class func method"); 
      }      
}

class InheritDemo{
      public static void main(String [] args){                      
            Derived d = new Derived();
            d.func(); 
      }
}


推荐答案

否,你没有压倒它。您可以尝试使用 @Override 进行标记,或尝试拨打 super.func(); 。两者都行不通;他们抛出了编译错误。

No, you are not overriding it. You can check by trying to mark it with @Override, or by trying to make a call to super.func();. Both won't work; they throw compiler errors.

此外,请检查一下:

class Base {
      private void func(){
            System.out.println("In base func method");         
      };
      public void func2() {
          System.out.println("func2");
          func();
      }
}

class Derived extends Base {
      public void func(){   //  Is this an overriding method?
            System.out.println("In Derived Class func method"); 
      }
}

class InheritDemo {
      public static void main(String [] args) {
            Derived D = new Derived();
            D.func2(); 
      }
}

它将打印:

func2
In base func method

当你将 func()更改为 Base 更改为public,然后它将成为覆盖,并且输出将更改为:

When you change func() in Base to public, then it will be an override, and the output will change to:

func2
In Derived Class func method

这篇关于可以在子类中重写超类中的私有方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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