Constructor help

How does the compiler handle constructors?

Q: If, when defining a class, we don’t define its constructor, the compiler implicitly assigns one. However, if we do define a constructor, the compiler interprets this as function overriding and does not flash an error. But if this is the case, why do I receive a compiler error in example 3 below?

Example 1:

class x
{
   int x,y;
   public void x( )  // The compiler considers this method overriding.
   {
       
   }
}
 
public static void main(String arg[])
{
   x x1=new x()   // No error.
}

Example 2:


class x
{
   int x,y;
   public  x( )  // The compiler considers this method overloading.
   {
       
   }
  public  x( int a, int b )  // The compiler considers this method overloading.
   {
       x = a;
       y= b;
   }
}
 
public static void main(String arg[])
{
   x x1=new x()        // No error
  x x1=new x( 5, 6 )   // No error
}

Example 3:

class x
{
   int x,y;
   public  x( int a, int b )              
   {
       x = a;
       y= b;
   }
}
 
public static void main(String arg[])
{
   x x1=new x()        // Why is there an error here?
  x x1=new x( 5, 6 )   // No error
}

A: First, if you do not define any constructors, Java will insert a default no-arguments constructor of the form:

public \<ClassName\*gt;()
{
   super();
}

Second, if you declare constructors, what you see is what you get. This means that if you don’t explicitly declare a no-arguments constructor but declare some other constructor, you will only get the constructor that you do explicitly define. This is why you see an error in example 3. Since you’ve never declared a no-arguments constructor but did define another type of constructor, Java does not insert a no-arguments constructor.

For example 3 to work you must also explicitly declare the no-arguments constructor:

public x()
{
   super();
}

Finally, subclasses do not inherit constructors. You must explicitly define each constructor that you need. Further, you can only call superconstructors that actually exist in the base class, in accordance with the rules that I outlined above.

Learn more about this topic

Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more