• Post Reply Bookmark Topic Watch Topic
  • New Topic

Please clarify this regarding super class construcors  RSS feed

 
vatsalya rao
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
Suppose we have a super class and a sub class extended from it.

Have a look at this code:


class constrDemo
{

public static void main(String args[])
{

}//end main()

}//end class definition


class superClass
{
int x;
superClass(int x)
{
this.x = x;
}

superClass(int x,int y)
{
}

superClass()
{

}

}//end class superClass



class subClass extends superClass

{

subClass(int x)
{
super(x);//line 1
}//end constructor

subClass(int x,int y)
{
super(x,y);//line 2

}


}//end class SubClass


In the above code in Superclass If i remove "no arg" constructor and comment Line 1 and Line 2,Iam getting error.

If I put no arg constructor in Super class and comment these lines, code is compiling fine.

My doubt is

In super class if there is no "no-arg" constructor then in subclass construtors we must call subclass' couter part of constructor in super class(if their access permits)?
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first line of code in EVERY constructor (except for Object's) is either a call to super(X) or this(X), where X is any combination of arguments (e.g. super(x, y), this(x)).

If you omit both the call to super(X) and this(X), the compiler will automatically insert a call to super(), without arguments. If that constructor does not exist in the super class then you must specify the constructor you want to call.
 
Vinayak patil
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Building on Rob's reply:

If you do not specify any constructor in your code, a default no args constructor will be created for you. But if you specify a constructor that takes arguments, no default constructor is created. You have to specify one explicitly.

Since you have not done so and by default the extended class constructor calls the default super class constructor, the error is thrown.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!