0

I am writing a couple of interfaces for tree data structure. I am getting Cannot make a static reference to the non-static type E compilation error.

Here is my interface hierarchy:

package com.mohit.dsa.global.position;

/**
 * @author mohitkum
 */
public interface Position<E> {
    public E getElement() throws IllegalStateException;
}

--

package com.mohit.dsa.tree;

import com.mohit.dsa.global.position.Position;

public interface Tree<E> extends Iterable<E> {
    Position<E> root;//compilation error for E
}

It will be great if someone can explain the cause of this error.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
mohit kumar
  • 179
  • 2
  • 10

1 Answers1

2

When you have a field in an interface, it is public static final. So Position root; (even without generics) is invalid in an interface. Further lets assume you are initializing the final field root and say your Tree interface is implemented as:

class A1 implements Tree<A>

class B1 implements Tree<B>

This would become a problem right? Since this would translate to:

Position<A> root in one case Position<B> root in another case

but your field is final so this cant work.

The below thread is related: Java - An interface that has static field pointing to class name of its sub class?

Community
  • 1
  • 1
Akshay Gehi
  • 362
  • 1
  • 12