It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes constructor call Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "constructor call" Watch "constructor call" New topic

constructor call

muskaan gaffor
Ranch Hand

Joined: May 19, 2006
Posts: 50
can we call constructor inside a constructor?

public Hello(){
title +="world";
public Hello(int value){
title = "Hello";
Hello(5); // line # 1
//Hello(); // line # 2

line # 1 - throws compilation err saying Hello(int) is undefined for the type Hello()

if I comment the line # 1 and use the line# 2 , am getting same compilation err --Hello() is undefined for the type Hello()

could any one please explain me?


ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
You can't invoke a Constructor explicitly, instead use "this()" within the same class or "super()" for invoking a super class Constructor, also you may pass any arguments indicating which one to invoke.
madapate reddy

Joined: Jan 28, 2008
Posts: 2
Constructors cannot be called make your code work properly make #2 as

new Hello();
madapate reddy

Joined: Jan 28, 2008
Posts: 2
To invoke the constructor from a constructor use this() for current class constructor if it is of parameterised then pass arguments to it or super() if you want to call a super class constructor and one of these statements should be first line of code.
I agree. Here's the link:
subject: constructor call
It's not a secret anymore!