prsubject
asked on
Is calling a default constructor mandatory
I have two classes. One class extends the other. In the subclass, I have two constructors. One which is the default constructor and the other which takes a String parameter . When I instantiate the class with a string parameter, it is calling both the constructors. I am pasting my code
//Code 1
public class Building {
Building()
{
System.out.println("B");
}
Building(String name)
{
this();
System.out.println("BN... "+name);
}
}
//Code 2
public class Ch1 extends Building{
static String name="Prasad";
Ch1()
{
System.out.println("Ch1...");
}
Ch1(String name)
{
this();
System.out.println("Ch1.."+name);
}
public static void main(String[] args)
{
new Ch1("XX ");
}
}
//Output
B
Ch1...
Ch1..XX
Within the subclass you can call
the constructor of your superclass using operator
super()
or
super(String)
as you superclass has bot constructors,
but youll cal only one of the two
and super opertaort shoudl always be
the very first operator in the
constructor of the subclass
ASKER
As You said I replaced the this() method in the subclass with super() method. Two Situations have arisen
Situation 1:
When I placed super() --> It was calling the default constructor of the super class --> Fine
Situation 2:
When I placed the first line with a parameterized constructor, super(name), It was calling both the default and the parameterized constructor of the super class.
//Output for second situation
B
BN... XX
Ch1..XX
Situation 1:
When I placed super() --> It was calling the default constructor of the super class --> Fine
Situation 2:
When I placed the first line with a parameterized constructor, super(name), It was calling both the default and the parameterized constructor of the super class.
//Output for second situation
B
BN... XX
Ch1..XX
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
within teh constructor which takes the string as parameter