Why a non static member class can be defined in an interface

Non-static member classes are defined as instance members of other classes, just like fields and instance methods are defined in a class. An instance of a non-static member class always has an enclosing instance associated with it.
An interface can't be instantiated then how a non static member class will have an enclosing instance associated with it.
interface outer
        public  class inner{
        public void p()
            System.out.println("inside interface's non static member class");
    public  static class inner1{
            public void p(){System.out.println("inside interface's  static member class");
public class Client {                                           // (11)
    public static void main(String[] args) {                    // (12)
    outer.inner nonStatic = new outer.inner();
        nonStatic.p();
    outer.inner1 stat = new outer.inner1();
      stat.p();
}inner is a non static member class even then " outer.inner nonStatic = new outer.inner();" working fine ?????????????

class outer
        public  class inner{
        public void p()
            System.out.println("inside interface's non static member class");
public class Client {                                           // (11)
    public static void main(String[] args) {                    // (12)
    outer.inner nonStatic = new outer.inner();
    nonStatic.p();
}on compiling the above code the error message i got is
"not an enclosing class: outer"
the reason of this compilation error is "outer.inner nonStatic = new outer.inner();
it should be "outer.inner nonStatic = new outer(). new inner();"
now my question is
interface outer
        public  class inner{
        public void p()
            System.out.println("inside interface's non static member class");
public class Client {                                           // (11)
    public static void main(String[] args) {                    // (12)
    outer.inner nonStatic = new outer.inner();
    nonStatic.p();
}on compiling the above code why compilation error is not coming??????????
i think now it is more clear what i am asking

Similar Messages

  • [SOLVED] Passing a non-static member function as a function pointer

    I need to pass a function pointer to a public method to a system call, nftw() to be precise.
    I know that member functions don't match the required signature because of the hidden 'this' pointer, but
    the only way to work around that is by using a small wrapper function that makes use of a global variable (the object of which I want to call the method).
    Speaking in code, this is the way I've solved the problem currently:
    // create a global variable here
    static MyObject obj;
    static int myObject_method_wrapper(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf) {
    return obj.handleDirEntry(fpath, sb, tflag, ftwbuf);
    // somewhere in main()
    nftw(walkroot, myObject_method_wrapper, 20, FTW_PHYS);
    Now, my question: Can't this be done without a global instance of MyObject? It is pointed out here that other ways are existent, but sadly they are not mentioned.
    Glad if someone could help me out!
    Last edited by n0stradamus (2012-04-24 22:59:47)

    I think you are stuck:
    1. You are not in control of the interface (of nftw), and furthermore,
    2. You are not in control of any of the parameters sent to the callback.
    nftw has no idea which one of your objects it is supposed to reference, and
    there's no apparent way to tell it.
    But given this situation, are you sure it makes sense to use a non-static
    member?  It seems kind of strange to me-- any instance-specific data is
    necessarily going to be independent of the function calls!  So even if you
    engineer something to avoid using a global, whatever you engineer is still
    going to involve some *arbitrary* instance of your class (e.g. peterb's
    solution, which uses the most recently created instance).  The arbitrary-ness
    doesn't feel right, since it sort of implicitly says that none of the instance
    data is important.  No important instance-specific data sounds like static...

  • Static nested class VS non-static nested class ??

    we know static method can be called without creating an object and static variables are shared among objects.
    what is the difference between static nested class and non-static nested class ? When do we use them? what is the advantages of static nested class over non-static nested class in term of performance?

    From the JLS, chapter 8:
    A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
    This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
    So "nested" iff "not top level".From the JLS, chapter 8:
    An inner class is a nested class that is not explicitly or implicitly declared static.
    So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
    ~

  • A question about non-static inner class...

    hello everybody. i have a question about the non-static inner class. following is a block of codes:
    i can declare and have a handle of a non-static inner class, like this : Inner0.HaveValue hv = inn.getHandle( 100 );
    but why cannot i create an object of that non-static inner class by calling its constructor? like this : Inner0.HaveValue hv = Inner0.HaveValue( 100 );
    is it true that "you can never CREATE an object of a non-static inner class( an object of Inner0.HaveValue ) without an object of the outer class( an object of Inner0 )"??
    does the object "hv" in this program belong to the object of its outer class( that is : "inn" )? if "inn" is destroyed by the gc, can "hv" continue to exist?
    thanks a lot. I am a foreigner and my english is not very pure. I hope that i have expressed my idea clearly.
    // -------------- the codes -------------------
    import java.util.*;
    public class Inner0 {
    // definition of an inner class HaveValue...
    private class HaveValue {
    private int itsVal;
    public int getValue() {
    return itsVal;
    public HaveValue( int i ) {
    itsVal = i;
    // create an object of the inner class by calling this function ...
    public HaveValue getHandle( int i ) {
    return new HaveValue( i );
    public static void main( String[] args ) {
    Inner0 inn = new Inner0();
    Inner0.HaveValue hv = inn.getHandle( 100 );
    System.out.println( "i can create an inner class object." );
    System.out.println( "i can also get its value : " + hv.getValue() );
    return;
    // -------------- end of the codes --------------

    when you want to create an object of a non-static inner class, you have to have a reference of the enclosing class.
    You can create an instance of the inner class as:
    outer.inner oi = new outer().new inner();

  • About static member class?

    I can unstand the technical detail about static member class. But i still have a question about it.The questionis when shall we use it when we design a poject. In another word, in which situation, static member class will show its advantage? Thanks a lot.

    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=static+nested+class&col=javaforums

  • Static member-class varaiable instanciation

    Hello,
    I have an inner class which I'm trying instanciate as a static variable. here is the code:
    public class A {
    protected static B b;
    private A (){} //private constructor because B is singleton
    class B {
    //some code
    =========================================================
    I cannot say
    protected static B b = new B();
    because new operator returns this.new_instance_of_B, and "this" cannot be referenced from the static constant...
    How can I instanciate this variable (b)?? Thank you,
    Elana

    You could make the class static but depending on how the class is written you might be better off just instatiating b in your constuctor. I question declaring b protected. You can not subclass a singleton (no public constructor), therefore there is no reason to declare b protected. If you want other classes to access b from inside the package just use package level (default) access. Having a static member of a singleton that isn't private seems to violoate the purpose of the Singleton pattern though. I don't know what you are trying ot do but I would declare your class like this.
    public class A {
        private static B b;
        private A (){
            b = new B();
        private class B {
            //some code
    }

  • SessionBean class can be defined static?

    Can we define session bean class 'static'.In the EJB specification I cannot find any limitation on not defining a session bean class as static.
    regards
    ashish

    Without more info of the other bits of your system
    then it's hard to say what's best.
    How are you accessing your database? Are you using
    Entity Beans? CMP?
    If so, you should use a session bean to help with
    transactions.The current design is that for each list, I'm using a Stateful Session bean that contains a Vector of CMP EJB references. This list is what I would prefer to not have each session recreate as some of the lists contain hundreds of items (EJB's). It would be desirable in terms of memory and performance to create these Session beans intitially and have every session continue to reference them without having to recreating for each session.
    But even so, if the application-level non EJB class representing the list contained EJB references, what happens when the session they were initially created under goes away? Will the container still hold a reference to these objects?
    Like I said, I can make all these list objects and the objects they reference static application-level standard beans and create them only the first time they are referenced, but that circumvents using the container and EJB's for this part of the architecture.

  • How to invoke a non-static member from a static reference?

    Hello JDC
    My program consist of several classes. I find it more readable,logic and useful to declare all the methods in all the classes �static� and get access by Class.member().
    The problem showed up when I must use a java biuld-in method( as Component.remove ) within my static method , then I receive compile error.
    The first alternative is to create the class instance inside the static my static method , the second is to use interface which declare its member as static final. The two ways doesn�t fit to my needs , do anyone know another way?
    Thanks in advance
    Shay

    Hi
    im sorry but im not sure what you mean by "OO desgin". i'll appreciate if you'll link me some sources about this , its sound very interesting .
    It may be that you are moving to Java from COBOL or >FOTRAN or something and you are not comfortable with >OO philosophy
    For example, you can never have two instances of >the same class have different properties. What's the >point of having classes at all if you are going to do it >this way? Java is my first language , you sound very unhappy about the way i ignore the OOP , i think you right in some terms but i need to exam my thinking again and think how can i implements the same ideas in a form of OOP. whenever all those information will come i'll be able to response.
    thanks for your reply
    Shay Gaghe

  • Why a static class can implements a non-static interface?

    public class Test {
         interface II {
              public void foo();
         static class Impl implements II {
              public void foo() {
                   System.out.println("foo");
    }Why a static class can implements a non-static interface?
    In my mind, static members cann't "use" non-static members.

    Why a static class can implements a
    non-static interface?There's no such thing as a non-static member interface. They are always static even if you don't declare them as such.
    An interface defines, well, a public interface to be implemented. It doesn't matter whether it is implemented by a static nested class or by an inner class (or by any class at all). It wouldn't make sense to enforce that it should be one or the other, since the difference between a static and non-static class is surely an irrelevant detail to the client code of the interface.
    In my mind, static members cann't "use" non-static
    members.
    http://java.sun.com/docs/books/jls/third_edition/html/classes.html#246026
    Member interfaces are always implicitly static. It is permitted but not required for the declaration of a member interface to explicitly list the static modifier.

  • Non-static method cannot be referenced from a static context....again sry

    Hey, I know you guys have probably seen a lot of these, but its for an assignment and I need some help. The error I'm getting is: non-static method printHistory() cannot be referenced from a static context. Here are the classes effected
    public class BankAccount {
    private static int nextAccountNumber = 1000;
    //used to generate account numbers
    private String owner; //name of person who owns the account
    private int accountNumber; //a valid and unique account number;
    private double balance; //amount of money in the account
    private TransactionHistory transactions; //collection of past transactions
    private Transaction transaction;
    //constructor
    public BankAccount(String anOwnerName){
    owner = anOwnerName;
    accountNumber = nextAccountNumber++;
    balance = 0.0;
    transactions = new TransactionHistory();
    //public String getOwner() {
    public void deposit(double anAmount ){
         balance=balance+anAmount;
         transaction=new Transaction(TransactionType.DEPOSIT,accountNumber,anAmount,balance);
         transactions.add(transaction);
    //public void withdraw(double anAmount){
    //public String toString() {
    ***public void printHistory(){
         TransactionHistory.printHistory();
    AND
    public class TransactionHistory {
    final static int CAPACITY = 6; //maximum number of transactions that can be remembered
    //intentionally set low to make testing easier
    private Transaction[] transactions = new Transaction[CAPACITY];
    //array to store transaction objects
    private int size = 0;
    //the number of actual Transaction objects in the collection
    public void add(Transaction aTransaction){
         if (size>5){
         transactions[0]=transactions[1];
         transactions[1]=transactions[2];
         transactions[2]=transactions[3];
         transactions[3]=transactions[4];
         transactions[4]=transactions[5];
         transactions[5]=aTransaction;     
         transactions[size]=aTransaction;
         size=size++;
    public int size() {
         return size;
    ***public void printHistory() {
         for(int i=0;i<6;i++){
              System.out.println(transactions);
    //public void printHistory(int n){
    The project still isn't finished, so thats why some code is commented out. The line with *** infront on it are the methods directly effected, I think. Any help would be great.

    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term +instance+ is often substituted for +non-static+, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    ~

  • Static nested class

    Hi there.
    Im playing around with static nested classes:
    class OuterC {
         int x = 10;
         static class Nest {
              void doStuff() {
                   System.out.println("Going");
                   //System.out.println("Should be allowed print: " + x);
                   doOtherStuff();
              public void doOtherStuff() {
                   System.out.println("Doing Stuff!");
    public class Test {
         static class OtherNest {
              void arbitraryMethod() {
                   System.out.println("Going to do arbitrary stuff...");
         public static void main(String[] args) {
              OuterC.Nest n = new OuterC.Nest();
              n.doStuff();
              OtherNest on = new OtherNest();
              on.arbitraryMethod();
    }//close TestWhen I uncomment the statement to print out the instance variable x of class OuterC
    I get a "cannot access non-static..." error, which is fine. I expect that.
    But why can I run the doOtherStuff() method from the static nested class Nest?
    doOtherStuff() is after all an instance method...
    Many Thanks & regards!
    Edited by: Boeing-737 on May 29, 2008 10:27 AM
    Dont bother replying, I see the error now. The method is defined as a member within the nested
    class. Apologies, I didn't spot that. My mistake.
    Thanks.
    Edited by: Boeing-737 on May 29, 2008 10:28 AM

    From the JLS, chapter 8:
    A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
    This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
    So "nested" iff "not top level".From the JLS, chapter 8:
    An inner class is a nested class that is not explicitly or implicitly declared static.
    So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
    ~

  • Calling non-static command from within static method

    Hello,
    I have a static method that reads bytes from serial port, and I want to set a jTextField from within this method. but I get error that says it is not possible to call non static method from a static one. How can it be solved?

    ashkan.ekhtiari wrote:
    No, MTTjTextField is the name of jTextFiled class instance.You haven't declared any such variable in the class you posted, not to mention that such a variable name violates standard code conventions.
    This is and instance of that object actually. You haven't declared any such variable in the class you posted.
    the problem is something else. No, it isn't, based on the information you have provided. If you want accurate guidance, don't post misleading information about your problem.
    It can not be set from within static method.A question commonly asked on Java forums concerns an error message similar to the following:
    non-static variable cannot be referenced from a static context
    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term instance is often substituted for non-static, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    Once you understand this concept, you can fix your own problem.
    ~

  • Non-static method cannot be referenced from a static context

    Hey
    Im not the best java programmer, im trying to teach myself, im writing a program with the code below.
    iv run into a problem, i want to call the readFile method but i cant call a non static method from a static context can anyone help?
    import java.io.*;
    import java.util.*;
    public class Trent
    String processArray[][]=new String[20][2];
    public static void main(String args[])
    String fName;
    System.out.print("Enter File Name:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    fName="0";
    while (fName=="0"){
    try {
    fName = br.readLine();
    System.out.println(fName);
    readFile(fName);
    catch (IOException ioe)
    System.out.println("IO error trying to read File Name");
    System.exit(1);
    public void readFile(String fiName) throws IOException {
    File inputFile = new File(fiName); //open file for reading
         FileReader in = new FileReader(inputFile); //
    BufferedReader br = new BufferedReader(
    new FileReader(inputFile));
    String first=br.readLine();
    System.out.println(first);
    StringTokenizer st = new StringTokenizer(first);
    while (st.hasMoreTokens()) {
    String dat1=st.nextToken();
    int y=0;
    for (int x=0;x<=3;){
    processArray[y][x] = dat1;
    System.out.println(y + x + "==" + processArray[y][x]);
    x++;
    }

    Hi am getting the same error in my jsp page:
    Hi,
    my adduser.jsp page consist of form with field username,groupid like.
    I am forwarding this page to insertuser.jsp. my aim is that when I submit adduser.jsp page then the field filled in form should insert into the usertable.The insertuser.jsp is like:
    <% String USERID=request.getParameter("id");
    String NAME=request.getParameter("name");
    String GROUPID=request.getParameter("group");
    try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
    PreparedStatement st;
    st = con.prepareStatement("Insert into user values (1,2,4)");
    st.setString(1,USERID);
    st.setString(2,GROUPID);
    st.setString(4,NAME);
    // PreparedStatement.executeUpdate();//
    }catch(Exception ex){
    System.out.println("Illegal operation");
    %>
    But showing error at the marked lines lines as:non static method executeupdate can not be referenced from static context.
    Really Speaking I am newbie in this java world.
    whether you have any other solution for above issue?
    waiting Your valuable suggestion.
    Thanks and regards
    haresh

  • Non-static method close() cannot be referenced from a static context

    Friends,
    I am having a little help with some static and not static issues.
    I created a JMenuBar, it's in the file: SlideViewMenu.java
    One of the operations is File->Close and another is File->Exit.
    The listener is in the SlideViewMenu.java file. The listener needs to reference two non-static methods within SlideView.java.
    Here's some of the code:
    SlideViewMenu.java
    public class SlideViewMenu {
        public JMenuBar createMenuBar() {
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
         // All the menu stuff works fine and is taken care of here.
       // Listener for Menu
       class MenuActionListener implements ActionListener {
         public void actionPerformed (ActionEvent actionEvent) {
              String selection = (String)actionEvent.getActionCommand();
             if (selection.equals("Close"))
              SlideViewFrame.close();
             else  SlideViewFrame.exit();
    }SlideView.java
    // Driver class
    public class SlideView {
         public static void main(String[] args) {
              ExitableJFrame f = new SlideViewFrame("SlideView");
                    // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame {
            // some things here, work fine.
         private SlideViewMenu menuBar = new SlideViewMenu();
         public SlideViewFrame(String title) {
         // Set title, layout, and background color
         super(title);
         setJMenuBar(menuBar.createMenuBar());
            // Stuff here works fine.
         // Handles doing stuff once the file has been selected
         public void setFileName(File fullFileName, String simpleName) {
            // Stuff here works fine.     
         // File->Close. clean up everything.
         public void close() {
              setTitle("SlideView");
              textArea.setText("");
              scrollBar.setVisible(false);
              textArea.setVisible(false);
              statsPanel.setVisible(false);
         // File->Exit.     
         public void exit() {
              System.exit(0);
    }The error I'm getting is:
    SlideViewMenu.java:50: non-static method close() cannot be referenced from a static context
    I don't get it?
    Thanks for all help.

    Making close() and exit() static would not solve the problem because close() requires access to nonstatic member variables/functions.
    Fortunately, that is not necessary. The real reason you are having a problem is that you don't have any way in your listener to access the main frame window, which is what the listener trying to control. You made a stab at gaining access by prefixing the function with the class name, but, as the compiler has informed you, that is only valid for static methods. If you think about it, you should see the sense in that, because, what if you had a number of frames and you executed className.close()? Which one would you close? All of them?
    Fortunately, there is an easy way out that ties the listener to the frame.
    SlideViewMenu.java:public class SlideViewMenu
      // Here's where we keep the link to the parent.
      private SlideViewFrame parentFrame;
      // Here's where we link to the parent.
      public JMenuBar createMenuBar(SlideViewFrame linkParentFrame)
        parentFrame = linkParentFrame;
        final Action openAction = new OpenAction();
        Action aboutAction = new AboutAction();
        ActionListener menuListener = new MenuActionListener();
        JMenuBar menuBar = new JMenuBar();
        // All the menu stuff works fine and is taken care of here.
      // Listener for Menu --- It is assumed that this is a non-static nested
      // class in SlideViewMenu. All SlideViewMenu variables are accessible from
      // here. If this is not the case, simply add a similar member variable
      //  to this class, initialize it with a constructor parameter, and
      // pass the SlideViewMenu parentFrame when the listener is
      // constructed.
      class MenuActionListener implements ActionListener
        public void actionPerformed (ActionEvent actionEvent)
          String selection = (String)actionEvent.getActionCommand();
          // Use parentFrame instead of class name.
          if (selection.equals("Close"))
              parentFrame.close();
            else
              parentFrame.exit();
    }SlideView.java// Driver class
    public class SlideView
      public static void main(String[] args)
        ExitableJFrame f = new SlideViewFrame("SlideView");
        // Stuff here, works fine.
    // Frame class
    class SlideViewFrame extends ExitableJFrame
      // some things here, work fine.
      private SlideViewMenu menuBar = new SlideViewMenu();
      public SlideViewFrame(String title)
        // Set title, layout, and background color
        super(title);
        //Here's where we set up the link.
        setJMenuBar(menuBar.createMenuBar(this));
      // Stuff here works fine.
      // Handles doing stuff once the file has been selected
      public void setFileName(File fullFileName, String simpleName)
        // Stuff here works fine.     
      // File->Close. clean up everything.
      public void close()
        setTitle("SlideView");
        textArea.setText("");
        scrollBar.setVisible(false);
        textArea.setVisible(false);
        statsPanel.setVisible(false);
      // File->Exit.
      public void exit()
        System.exit(0);
    }

  • Reinterpret_cast failed to cast between const and non-const member function

    The following code passes g++, but fails on Sun CC 5.8
    class C {
    public:
    void fv();
    void fc() const;
    typedef void (C::*C_FUNC)();
    typedef void (C::*C_CONST_FUNC)() const;
    int main()
    C_FUNC f1 = &C::fv;
    C_CONST_FUNC f2 = &C::fc;
    C_CONST_FUNC f3 = reinterpret_cast<C_CONST_FUNC>(&C::fv);
    C_FUNC f4 = reinterpret_cast<C_FUNC>(&C::fc);
    "recast.cc", line 15: Error: Cannot cast away const or volatile.
    "recast.cc", line 16: Error: Cannot cast away const or volatile.
    2 Error(s) detected.
    Is this a bug of Sun CC?
    Thanks.
    huoq.

    This is a bug in the Sun C++ compiler. A reinterpret_cast is not allowed to cast away constness, but the "const" on a non-static member func tion is not a "top-level" const, and is not being cast away.
    Please file a bug report at http://bugs.sun.com

Maybe you are looking for

  • How to Separate Date and Time

    Hi All, Iam New to Power Pivot,I have Date and Time in the Same Field (2014-09-04 19:20:37.637) and now i want Separate Date in one field and time in one Field.can any one Help on this. Ex:  (2014-09-04 19:20:37.637) Date                             

  • Question on spry vertical menu bar backgrounds

    I have a spry vertical menu bar.  The menu branches off to 3 or 4 levels in some cases.  When you mouse over the menu structure the menu path that you have selected turns a different color.  I acheived this by giving ul.MenuBarVertical a.MenuBarItemH

  • I am locked out of my new ipod touch 5 how do i get back in?

    Help - my daughter is locked out of her brand new ipod touch 5 she just got for x-mas. She can't remember the password she put on it. What can we do?

  • TS3274 My ipad always shows "NO SIM"  what do I do?

    I have a NO SIM message on my ipad now.  I don't know what to do.  Any sugguestions?

  • Export in Lightroom acting strange

    After many years of exporting jpegs at 300 ppi my Lightroom suddenly only exports at 72 ppi even though the image resolution is still set to 300 ppi. What could be the problem?