Marian Klühspies
Marian Klühspies

Reputation: 17647

Static array with inheriting classes in Java

I have a litte problem with a static, direct filled array of class files, which inheriting from a superclass

 public static Class<SuperClass> classes= new Class<SuperClass>[]{
    ChildClass.class
}

seems to be impossible. Intellij says, it requires the Superclass.class, instead of ChildClass.class.

Why is this not possible? Thank you

Upvotes: 0

Views: 73

Answers (3)

avidD
avidD

Reputation: 451

  1. There are no generic arrays. You cannot create an array of Class
  2. Class is not a subclass of Class

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

Arrays and generics don't mix.

Also a type Xx<Derived> is not assignable to Xx<Base> (see bazillions of questions on this site).

You may want:

private static final Class<? extends SuperClass> clazz = ChildClass.class;

The other way around:

private static final Class<? super ChildClass> clazz = SuperClass.class;

Or use an appropriate collection:

private static final Set<? extends SuperClass> classes =
    unmodifiableSet(singleton(
        ChildClass.class
    ));

Mutable statics, even if not public, are a really bad idea.

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35577

It is not possible because we use =(equal) to say left and right hand sides are same.. here you are assigning an array to a non-array variable.

Upvotes: 0

Related Questions