Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt regarding Constructors - - JLS

 
Neelkanth K
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Can somebody throw more light on this,
This is from JLS(page 178)
________________________________________________________________
Except for the possibility of explicit constructor invocations, the body of a constructor is like the body of a method (�8.4.5). A return statement (�14.15) may be used in the body of a constructor if it does not include an expression.
_________________________________________________________________
As far i know, constructors cannot return a value.
Please help, i am very cconfused.
Thanx
Neelkanth
 
Richard Agnes
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that's interesting, I wasn't aware of that, but it seems to work take a look output is 100:
public class Tester{
int m=100;
boolean b=true;

Tester(){
if(b){
return;
}
m+=100;
}


public static void main(String args[]){
Tester t=new Tester();
t.showM();
}

void showM(){
System.out.println(m);
}

}//end class
I guess it's to halt processing in the constructor.
 
Wasim Ahmed
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JLS is correct you can have empty "return" keyword in the constructor but you cannot assign any value to that return. On the other hand if you add return type in the constructor signature, that will turn into a method with the same name as class. (another strange act of JAVA)see the following example.
example:
class Aclass
{
Aclass()
{System.out.println("I am in Constructor");
return;
}
int Aclass()
{
System.out.println("I am in method");
return 4;
}
public static void main( String argv[] ){
Aclass a = new Aclass();
a.Aclass();
}
}
Output : I am in Constructor
I am in method
 
Neelkanth K
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Wasim & Richard,
Now i got it,
Thanks for explanation
Neelkanth
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your name 'Neelkanth K' does not comply with the JavaRanch naming policy. Please choose one that meets the requirements.
Thanks!
Ajith
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic