• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Usage of static with inner classes

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 2908
1
Spring Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 !
 
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:

reply
    Bookmark Topic Watch Topic
  • New Topic