graviton
graviton

Reputation: 463

Generic inner class with instance variable that is an object of another generic inner class

First, I realize that I can make ProblemClass a non-generic class and not receive a compiler error. I am wondering what this error means though. My code is very simple, a generic class with two private inner classes. The outer class has an instance variable of type InnerClass<E> and the inner class ProblemClass<E> also has an instance variable of type InnerClass<E>. When ProblemClass` is instantiated, all it does is set o = a, where o,a are the instance variables of the outer class and inner class respectively.

public class SuperClass<E> {

    private class InnerClass<E> {
    }

    private class ProblemClass<E> {
        private InnerClass<E> o;

        public ProblemClass() {
            o = a;
        }
    }

    private InnerClass<E> a;
}

I receive the following error.

SuperClass.java:11: error: incompatible types
            o = a;
                ^
  required: SuperClass<E#1>.InnerClass<E#2>
  found:    SuperClass<E#1>.InnerClass<E#1>
  where E#1,E#2 are type-variables:
    E#1 extends Object declared in class SuperClass
    E#2 extends Object declared in class SuperClass.ProblemClass
1 error

My question is, what does this error mean?

Upvotes: 2

Views: 534

Answers (3)

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

@IanRoberts has the answer, some of your E are not the same.

Here's a fixed version of your code:

public class SuperClass<SE> {

  private class InnerClass<IE> {
  }

  private class ProblemClass<PE> {
    private InnerClass<SE> o;

    public ProblemClass() {
      o = a;
    }

  }

  private InnerClass<SE> a;
}

Upvotes: 0

Ian Roberts
Ian Roberts

Reputation: 122364

Quite simply the E of ProblemClass and the E of InnerClass are not related - your code is equivalent to

public class SuperClass<E> {

    private class InnerClass<F> {
    }

    private class ProblemClass<G> {
        private InnerClass<G> o;

        public ProblemClass() {
            o = a;
        }
    }

    private InnerClass<E> a;
}

and you can clearly see that a and o are not necessarily compatible.

Upvotes: 4

SLaks
SLaks

Reputation: 887413

As the error is trying to tell you, you have two different Es that may be two different types.

What would happen if you create a new OuterClass<Integer>.ProblemClass<String>()?

Upvotes: 1

Related Questions