-7

i'm researching on how to make a parameter that accepts any object, i found an answer and i tried recreating the code. but the problem is whenever i initialize Bee,Horse and Apple it always shows the error "non-static variable cannot be initialized from a static context". so how is this wrong?

public class Testing{
public static void main(String[]args){
  Bee a= new Bee();
  Horse b= new Horse();
  Apple c= new Apple():
}
private interface holder{
    public int getX();
}
private class Bee implements holder{
    int a=52;
    public int getX(){
        return a;
    }
}
private class Horse implements holder{
    int a=62;
    public int getX(){
        return a;
    }
}
Zara suto
  • 1
  • 1
  • 3
  • You currently have inner classes, which require an instance of the outter class to instantiate. Make those classes `static`. – Vince May 31 '18 at 09:20
  • Seeing as you don't have an Apple class, how was this supposed to work in the first place? what exactly is the line the error is shown on? – Stultuske May 31 '18 at 09:20

1 Answers1

0

Just change the class definitions of Bee and Horse from:

private class Bee implements Holder {...}

to:

private static class Bee implements Holder {...}

without the static keyword the class is treated as an inner class and needs an instance of the enclosing class to be instantiated. E.g without static you'd have to write:

Testing testing = new Testing();
Bee bee = testing.new Bee();

Which doesn't make sense, because Testing and Bee aren't really related. So with the static it can be done like you tried:

Bee bee = new Bee(); // works
Lino
  • 19,604
  • 6
  • 47
  • 65