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();
    }
}

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

commented: true +4

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.