Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve this "non-static variable" issue in Java?

Tags:

java

interface

public class InterfaceTest {
    interface  InterfaceA {
         int  len =  1 ;
         void  output();
    }

    interface  InterfaceB {
           int  len =  2 ;
           void  output();
    }

    interface  InterfaceSub  extends  InterfaceA, InterfaceB {            }

    public class Xyz implements  InterfaceSub {

         public   void  output() {
            System.out.println( "output in class Xyz." );
        }

          public   void  outputLen(int  type) {
              switch (type) {
                      case  InterfaceA.len:
                             System.out.println( "len of InterfaceA=." +type);
                              break ;
                      case  InterfaceB.len:
                             System.out.println( "len of InterfaceB=." +type);
                              break ;
             }
        }
    }

    public   static   void  main(String[] args) {
           Xyz xyz = new Xyz();
           xyz.output();
           xyz.outputLen(1);
   }
}

Hi, I want to learn Java's interface and multiple inheritance concept. I found above code and try to compile it, but below error occurs. I don't know how to make the code work, who could help? Thanks!

test$ javac InterfaceTest.java 
InterfaceTest.java:33: error: non-static variable this cannot be referenced from a static context
           Xyz xyz = new Xyz();
                     ^
1 error
like image 205
Tom Xue Avatar asked Feb 27 '26 12:02

Tom Xue


1 Answers

This is because a non-static inner class cannot be instantiated in a static method because it does not have an instance of the enclosing class to work with.

If you define Xyz as a static inner class it should work:

public static class Xyz implements InterfaceSub {
  ....
}

Alternatively, you can create Xyz within an instance of the enclosing class - this is not needed here but this would be required if Xyz needed to access some member variables of the enclosing class.

like image 111
mikera Avatar answered Mar 01 '26 01:03

mikera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!