【问题标题】:Inheritance In Java [error when sub class declared as protected]Java中的继承[子类声明为受保护时出错]
【发布时间】:2014-04-19 09:12:17
【问题描述】:

困惑:

  • protected 修饰符主要用于继承机制 protected 我们可以扩展
  • 如果 super 在子类中更具限制性(私有),则获得特权可能会更少

    public class Sub extends Base //line 1
    {
      Sub()
       {
            System.out.println("Base Class");
       }
      public static void main(String[] args) 
       {
              System.out.println("Calling From Main");
              Base b = new Base()
              Sub s = new Sub();
        }
    }
    protected class Base        // line 14
    {
      Base()
        {
            System.out.println("Base Class");
        }
    }
    
  • 第 14 行的编译文件

    error: modifier protected not allowed here
    protected class Base
              ^
    1 error
    
  • 为什么会报错请解释一下?

  • 是否可以声明/扩展受保护的类?

【问题讨论】:

标签: java inheritance compiler-errors protected


【解决方案1】:

Protected 和 Private 类只能作为内部类和嵌套类。 在继承中,Protected用作方法或变量级别,而不是顶级类级别。

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 2010-09-14
    • 2016-02-29
    • 1970-01-01
    • 2020-09-14
    • 2016-04-18
    • 2011-05-24
    • 2014-01-30
    • 2018-08-23
    相关资源
    最近更新 更多