Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

local class in a static method

 
basha khan
Ranch Hand
Posts: 516
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
look the code ,
--------------------------------------------------
class localclassTest{
int a=10;
public static void main(String asd[]){
final int b=20;//(a)
class inner{
int a=30;
void print(){
int a=40;
System.out.println(a);//(1) local varable
System.out.println(this.a);// (2)inner class member variable
//System.out.println(t3.this.a);//(3) outer class member variable
}
}
new inner().print();
}}
---------------------------
what is wrong in //(3).why outer class member not availeable?
 
R K Singh
Ranch Hand
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println(t3.this.a);//(3) outer class member variable
I think t3 => localclassTest
then as 'a'(member var) is not static ..
do not confuse with inner class.. it is simple question which says that U CAN NOT access any NON-static member from static method.
CMIW
HTH
 
Shivaji Marathe
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are creating the inner class in a static method and within that inner class you are trying to access a non static member of the outer class without creating an instance of the outer class.
You need to create t3 as an instance of the outer class, before you refer to it .

[ January 31, 2002: Message edited by: Shivaji Marathe ]
 
Paul Salerno
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sivaji
System.out.println(t3.a);//(3) outer class member variable
I was under the im impression that you can't access a non-static variable within a static method main(), since the inner class and its method is within a static method main()
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're not accessing a non-static variable.
t3 is declared local to the method:
Foo t3= new Foo() ; // **** create t3 ****
System.out.println(t3.a);//(3) outer class member variable
You're accessing a member of a class through a local reference. This is perfectly legal.
Rob
[ January 31, 2002: Message edited by: Rob Ross ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic