【问题标题】:Can default visibility in Java Class have a protected member?Java 类中的默认可见性可以有一个受保护的成员吗?
【发布时间】:2014-12-31 00:25:41
【问题描述】:

在 Java 中,从我的角度来看,默认可见类拥有 protected 成员是没有意义的。在我看来,这没有意义,因为 Java 中的默认可见性 = 包级别 Java 中受保护的可见性 = 包级 + 子类(与包无关)

class TestClass{

 protected int addIntegers(int a, int b){

       return (a+b);
 } // end of protected addIntegers(int a, int b){

}

我说上面的代码是废话对吗?

【问题讨论】:

    标签: java default semantics protected


    【解决方案1】:

    您很可能在同一个包中拥有一个公共类 Foo,扩展您的 Base 类,并在另一个包中拥有另一个类 Bar,扩展 Foo 并覆盖受保护的方法。

    package a;
    
    class Base {
        protected void bang() {
        }
    }
    
    package a;
    
    public class Foo extends Base {
    }
    
    package b;
    
    public class Bar extends Foo {
        @Override
        protected void bang() {
        }
    }
    

    【讨论】:

    • 好渔获!!!所以这是一种在与默认可见类关联的包之外的类中查看属于默认可见类的受保护方法的方法。好抓!!!!
    猜你喜欢
    • 2012-09-26
    • 2011-12-25
    • 2012-08-08
    • 2010-11-17
    • 2013-08-06
    • 1970-01-01
    • 2022-07-20
    • 2018-09-03
    • 2017-11-27
    相关资源
    最近更新 更多