• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Non static methods of static inner class

 
Gayathri Ramanujam
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A
{
String y="AA";
public static void main(String[] args)
{
A x= new A();
A.Inner.Test();
}

static private class Inner{
private void Test(){
System.out.println("Test"+y);

}
}
}
 
Surendra Kumar
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This class won't compile as static inner class can not have access to instance members.
 
Gayathri Ramanujam
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you forget the y then I get this error

A.java:7: non-static method Test() cannot be referenced from a static context
A.Inner.Test();

I was wondering how to access Test()?
 
Surendra Kumar
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
new A.Inner().Test();
 
shilpa Reddy
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This works

class outer
{
String y="AA";
public static void main(String[] args)
{
outer x= new outer();
outer.Inner y = new outer.Inner();
y.Test();
}

static private class Inner{
private void Test(){
System.out.println("Test");

}
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic