简体   繁体   中英

Error -- Super class constructor in Eclipse with Java 8

I am coding in eclipse and new to java, inherited method and calling parent method with super() keyword showing error in Java-8 also the new Child(); method is also showing error. File name is 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");
        }
    }

it gives an error in 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).

. ; .

  • super(10); can only be used inside a constructor (not inside a method) to call the constructor of the super class (the class being extended), eg if you have Parent(int a) { ... } , you can do Child() { super(10); } Child() { super(10); } ; or if you want to call the existing method of the super class (instead of the non-existing super constructor with a single number parameter) use super.parentMethod(10); instead
  • new Child(); does not work inside a static method for a non- static nested class; a non-static inner class belongs to an instance of the outer class: new Example().new Child(); would work here instead; alternatively, since in the example the nested classes do not make use of instance methods and fields of Example , you can make the classes Parent and Child static to fix the error: static class Parent{ and static class Child extends Parent{

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM