可以在子类中覆盖超类中的私有方法吗? [英] Can a private method in super class be overridden in the sub-class?
本文介绍了可以在子类中覆盖超类中的私有方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以在 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
当您将 Base
中的 func()
更改为 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屋!
查看全文