1

I have this problem with my code and I don't know how to resolve it please help me. No enclosing instance of type Hra is accessible. Must qualify the allocation with an enclosing instance of type Hra (e.g. x.new A() where x is an instance of Hra)."

public class Hra {

    public static void main(String[] args) {
        Hrac h = new Cerveny(1); // there is that error 
        int result = h.zautoc(55, 30);
        System.out.print(0);
    }

    public Hrac[] pole;
    private int counter;

    public Hra() {
        this.pole = new Hrac[100];
        this.counter = 0;
    }

    public void pridajHraca(Hrac h) {
        this.pole[counter] = h;
    }

    public abstract class Hrac{

        protected double zivot;
        public int tim;

        public int zautoc(int velkost, int mojaPozicia){
            if (tim == 1){
                if (mojaPozicia >= 7)
                    return (mojaPozicia -7);
                else
                    return (velkost - 7 - mojaPozicia); 
            }
            if (tim == 2){
                if (mojaPozicia +3 <= velkost)
                    return (mojaPozicia +3);
                else
                    return (mojaPozicia -velkost +3 );  
            }
            return 0;
        }

    }

    public class Cerveny extends Hrac{
        public Cerveny(double _zivot) {
            super.zivot = _zivot;
            super.tim = 1;
        }
    }

    public class Cierny extends Hrac{
        public Cierny(double _zivot) {
            super.zivot = _zivot;
            super.tim = 2;
        }
    }
}
  • Possible duplicate of [No enclosing instance of type Server is accessible](http://stackoverflow.com/questions/7901941/no-enclosing-instance-of-type-server-is-accessible) – Raedwald Mar 02 '16 at 22:29
  • Possible duplicate of [Java - No enclosing instance of type Foo is accessible](http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible) – fabian Mar 03 '16 at 22:43

1 Answers1

2

You're using non-static nested classes, also known as inner classes. Instances of those classes need an instance of their inclosing classes to be constructed, as the message indicates:

Must qualify the allocation with an enclosing instance of type Hra (e.g. x.new A() where x is an instance of Hra

Looking at your code, these inner classes could be static nested classes, since they don't access any member of their inclosing class. Or even better, since you don't seem to know what nested classes are yet, and since I don't see any good reason for these classes to be nested, they should be top-level classes, defined in their own .java file. Don't use nested classes before understanding what they're for, and how they work.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255