Why is it that when I invoke the Derived constructor from the main method, I get a compilation error pointing to the Derived constructor of the Derived class. I never called the Base constructor of the Base class. Therefore why is the error happening?.

class Base 
{
     private Base() 
     {
          System.out.print("Base");
     }
}
public class Derived extends Base 
{
    public Derived() 
    {
         System.out.print("Derived");
    }

    public static void main(String[] args) 
    {
         new Derived();
    }
}

Edited 6 Years Ago by solomon_13000: n/a

The constructor in your Base class is private, which means that nothing outside of Base class (including derived classes) can access it. Changing the constructor to a different access modifier (such as public) will fix this. One thing to note about constructors is that the compiler will insert an implicit call to the constructor of a superclass, which will occur before the constructor of the base class executes. As the superclass's constructor is private, the subclass cannot access it. more info: http://java.sun.com/docs/books/tutorial/java/IandI/super.html

Edited 6 Years Ago by majestic0110: n/a

Comments

Why is it that when I invoke the Derived constructor from the main method, I get a compilation error pointing to the Derived constructor of the Derived class. I never called the Base constructor of the Base class. Therefore why is the error happening?.

class Base 
{
     private Base() 
     {
          System.out.print("Base");
     }
}
public class Derived extends Base 
{
    public Derived() 
    {
         System.out.print("Derived");
    }

    public static void main(String[] args) 
    {
         new Derived();
    }
}

end quote.

If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass in the subclass.
Here in your example the Base class constructor is private and so the automated invocation of constructor gives an access error.

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Why is it that when I invoke the Derived constructor from the main method, I get a compilation error pointing to the Derived constructor of the Derived class. I never called the Base constructor of the Base class. Therefore why is the error happening?.

class Base 
{
     private Base() 
     {
          System.out.print("Base");
     }
}
public class Derived extends Base 
{
    public Derived() 
    {
         System.out.print("Derived");
    }

    public static void main(String[] args) 
    {
         new Derived();
    }
}

private constructors are used in classes when no objects (or descandents) are expected to be created from them.

You would only use a private constructor for classes that offer only static members to a caller.

This article has been dead for over six months. Start a new discussion instead.