aspose file tools
The moose likes Java in General and the fly likes inner class within a method Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "inner class within a method" Watch "inner class within a method" New topic
Author

inner class within a method

Stu Higgs
Ranch Hand

Joined: Jan 01, 2006
Posts: 74
Hi,

Not sure if this i beginner or intermediate question.

I am currently studying and learing how to work with inner classes.

I was surprised when the follwoing code returned a string representationof the finalLocalVar when I did not call the toString() method directly. If anyone can elaborate on why this happens will appreciate it greatly. Thanks...

CODE:

public class Outer4 {

private int size = 5;

public Outer4(){}

public Object makeTheInner(int localVar){
final int finalLocalVar = 6;
//declare an inner class within a method
class Inner {
public String toString(){
//return " localVar="+localVar;//ERROR: ILLEGAL
return "finalLocalVar = "+finalLocalVar;//LEGAl
}
}//end inner class

return new Inner();//creat instance of Inner
}//end makeTheInner() method

public static void main(String[] args) {
Outer4 outer = new Outer4();
Object obj = outer.makeTheInner(47);
System.out.println("The object is "+obj+"\n");

}

}
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2341
Whenever you use an object reference in an SOP and/or with String concatenation, then an implicit call is made to the toString() of the object that it refers to.
[ July 01, 2006: Message edited by: Keith Lynn ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
"stringLiteral" + objectVariable

is translated by the compiler to something like

new StringBuffer().append("stringLiteral").append(objectVariable).toString();

StringBuffer.append(object) delegates to String.valueOf(object), if I remember correctly, which in turn will call object.toString() unless object is null.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Stu Higgs
Ranch Hand

Joined: Jan 01, 2006
Posts: 74
Thanks for your replies.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: inner class within a method
 
Similar Threads
final local variable and method inner class
Method-local Inner Class Q
Local Inner class
About inner classes....
Null pointer Exception