【问题标题】:Error -- Super class constructor in Eclipse with Java 8错误——Eclipse 中使用 Java 8 的超类构造函数
【发布时间】:2020-01-19 06:13:22
【问题描述】:

我在 Eclipse 和 Java 新手中编码,继承方法和调用父方法,super() 关键字在 Java-8 中显示错误,new Child(); 方法也显示错误。文件名为 Example.java

public class Example{
        class Parent{
            void parentMethod(){
                System.out.println("Parent Method");
            }
            void parentMethod(int a){
                    System.out.println("Parent Method: One Argument");
            }
            void parentMethod(int a, int b){
                        System.out.println("Parent Method: Two Argument");
            }
        }
       class Child extends Parent{
            void childMethod() {
                super(10);
                System.out.println("Child Method");
            }
        }
        public static void main(String[] args) {
            new Child();
            System.out.println("Main Class Method: no argument");
        }
    }

它在eclipse中给出了一个错误:

in line 15: Multiple markers at this line
    - Line breakpoint:Public$Child [line: 15] - 
     childMethod()

in line 20: No enclosing instance of type Public is accessible. Must qualify the allocation with an enclosing 
 instance of type Public (e.g. x.new A() where x is an instance of Public).

。 ; .

【问题讨论】:

  • 这不是你声明公共类的方式public class Parent & public class Child extends Parent
  • 还是报错
  • 你为什么首先使用内部类?什么目的?你想用super(10);做什么?

标签: java eclipse inheritance java-8 super


【解决方案1】:
  • super(10); 只能在构造函数内部(不能在方法内部)调用超类(被扩展的类)的构造函数,例如如果你有Parent(int a) { ... },你可以做Child() { super(10); };或者如果你想调用超类的现有方法(而不是具有单个数字参数的不存在的超级构造函数),请改用super.parentMethod(10);
  • new Child(); 在非static 嵌套类的static 方法中不起作用;一个非静态内部类属于外部类的一个实例:new Example().new Child(); 将在这里工作;或者,由于在示例中嵌套类不使用 Example 的实例方法和字段,您可以将类 ParentChild 设为静态以修复错误:static class Parent{static class Child extends Parent{

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2014-11-06
    • 2010-09-29
    • 1970-01-01
    • 2013-10-20
    相关资源
    最近更新 更多