开发者

How to resolve 'Implicit super constructor classA() is not visible. Must explicitly invoke another constructor'?

I am having a class 'ClassA' which is having private constructor.

public final class ClassA{
  private ClassA{
  }

  public static void main(String[] arg) }{
  ;
  ;
  ;
  }
}

Now, i am extending the class 'ClassA' [ final keyword is removed before doing this ]

public class ClassB extends ClassA{
     public static void main(String[] arg) }{
      ;
      ;
      ;
      }

}

No开发者_如何学Cw, i am getting Implicit super constructor classA() is not visible. Must explicitly invoke another constructor. What does it mean and how to resolve this?

Note i can not change the access specifier of ClassA constructor.


Change the constructor visibility of ClassA from private to protected.

Constructors always begin by calling a superclass constructor. If the constructor explicitly contains a call to a superclass constructor, that constructor is used. Otherwise the parameterless constructor is implied. If the no-argument constructor does not exist or is not visible to the subclass, you get a compile-time error.


I would suggest composition instead of inheritance (maybe that's what the designer of ClassA intended for class usage. Example:

public class ClassB {
   private ClassA classA;

   ClassB() {
       // init classA
       ...
   }

   public ClassA asClassA() {
       return classA;
   }

   // other methods and members for ClassB extension
}

You can delegate methods from ClassB to ClassA or override them.


Java will implicitly create a constructor with no parameters for ClassB, which will call super(). In your case the constructor in ClassA is not visible, hence the error you are getting. Changing the visibility to public or protected will resolve the error.


Changing private ClassA{} to protected ClassA{} sounds like a good solution.

Parent constructor is always called in child class: implicitly or not. So, your ClassB definition is equivalent to

public ClassB extends ClassA {
    public ClassB() {
        super();
    }

    // all other methods you have go here...
}

If the only constructor of ClassA is private, it can't be called from ClassB.


Because the son must invoke father's constructor for Complete the initialization of the parent's parameters.

Now ClassA is final class and it's constructor is private.If ClassB extends ClassA.

  1. remove final of the ClassA
  2. invoke super() or super(**), change private to public/protected, or add constructor for ClassA
public class ClassA {
    private ClassA() {
    }

    // add
    protected ClassA(String str) {
    }

    public void display() {
        System.out.println("Father's display");
    }
}
class ClassB extends ClassA {
    public ClassB() {
        // add
        super(null);
    }

    public void display() {
        System.out.println("Son's display");
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜