• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor call

 
muskaan gaffor
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can we call constructor inside a constructor?

Like
public Hello(){
title +="world";
}
public Hello(int value){
this.value=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?

regards,
Mussy.


}
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
Constructors cannot be called explicitly.to make your code work properly make #2 as

new Hello();
 
madapate reddy
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic