| 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.
|
 |
 |
|
|
subject: inner class within a method
|
|
|