aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Usage of static with inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Usage of static with inner classes" Watch "Usage of static with inner classes" New topic
Author

Usage of static with inner classes

Sekhar Choudary
Ranch Hand

Joined: May 03, 2008
Posts: 57
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

Joined: Feb 19, 2008
Posts: 2902
    
    1

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 !


[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
Vlado Zajac
Ranch Hand

Joined: Aug 03, 2004
Posts: 245
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

Joined: Jul 05, 2008
Posts: 141
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:



SCJP Java 6 (98%) - Story, SCJA (88%) - Story
 
Don't get me started about those stupid light bulbs.
 
subject: Usage of static with inner classes