无法从父级减少方法继承方法的可见性 [英] Cannot reduce visibility of method inherited method from parent

查看:258
本文介绍了无法从父级减少方法继承方法的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个编译器错误:

I got this compiler error:


您无法降低继承方法的可见性。

You cannot reduce the visibility of a inherited method.

我有以下代码

class Parent {      
    public void func() {
        System.out.println("in Parent");
    }
}

public class TestClass extends Parent {    
    public static void main(String args[]) {
        parent obj=new TestClass();
        obj.addTest();
    } 

    private void func() {
        System.out.println("in child");         
    }
}

这里的父类有 func ()公共的方法,由子类 TestClass 覆盖,这是私有的。现在编译器抛出了我无法降低可见性的错误。从技术上说,每当我创建一个 TestClass 的对象时,分配给类型父对象,因为 func()方法被重写,TestClass的func()总是被调用,那么为什么我们应该关注可见性呢?这个错误背后的原因是什么?有人可以清楚解释一下吗?

Here parent class has func() method which is public and overridden by the subclass TestClass which is private. Now the compiler throws the error that I cannot the reduce the visibility. To say technically, whenever I create a object of TestClass assigning to the type parent object, since the func() method is overridden, TestClass's func() is going to get called always, then why we should take care of visibility? whats the reason behind this error ? Can someone explain me clearly ?

推荐答案

这是因为子类具有 private 对于 void func()方法,但超类的可见性 public

It's because the subclass has visibility of private for the void func() method, but the superclass has visibility public.

如果你的代码被允许编译,如果你这样做,它会在运行时爆炸:

If your code was allowed to compile, it would explode at runtime if you did this:

parent p = new TestClass();
p.func(); // boom - func is public in parent, but TestClass's impl is private, so no access would be allowed

要修复这个,请使子类的 func 方法公开

To "fix" this, make the subclass's func method public:

public class TestClass extends parent {
    ...
    public void func() { // give it public visibility
        System.out.println("in child");         
    }
}



请使用标准命名约定;在这种情况下,类应该以大写字母开头 - 即不是

这篇关于无法从父级减少方法继承方法的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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