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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With