• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Usage of static with inner classes

 
Sekhar Choudary
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

class Outer1{
String ov="outer1 var";
Inner1 iob=new Inner1();
class Inner1{
Inner1(){ System.out.println("Inner1 cons"); }
public void im1(){ System.out.println("inner1 method im1::"+ov+" "+iv); }//im1
String iv="inner var";
}//inner1
public static void om1()
{ System.out.println("Outer1 method om1");
//new Inner1().im1(); line #1
// or even for
//Inner1 o=new Inner1(); o.im1(); same error line #2
}

public static void main(String[] args){
Outer1.Inner1 ob=new Outer1().new Inner1();
ob.im1();
om1();
Outer1 o=new Outer1();
o.om1();
}//main
}//class

Hi when i compile the above source code,compiler is pointing out two errors each at line#1 and line# 2 as follows
" Non static variable this cannot be referenced from static context"

Can't we access the instance method from static method using object of that class??

Thanks.
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The error explains it all, In static methods, Java allowed to give access to only static members . So to run this code, make your im1() method a static one ! and please use code tags to surround tho code snippet !
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instance of outer class is required to create an instance of inner class.

So it static method you cannot use

but something like this is needed:
 
Raphael Rabadan
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vlado Zajac:
Instance of outer class is required to create an instance of inner class.

So it static method you cannot use

but something like this is needed:


Just an adittion, you could make this code work making the method an instance method.

Take a look at this code:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic