We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Is calling a default constructor mandatory

prsubject
prsubject asked
on
Medium Priority
295 Views
Last Modified: 2012-08-13
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

Open in new window

Comment
Watch Question

Awarded 2011
Awarded 2011

Commented:
No it is not mandatory - you don't need to call default constructor
within teh constructor which takes the string as parameter
Awarded 2011
Awarded 2011

Commented:

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


Author

Commented:
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
Awarded 2011
Awarded 2011
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.