"Cannot subclass the final class" error, but the class is not final

8k views Asked by At

Here is my code:

package basic;

public abstract class Entity {}

package characters;

import basic.Entity;

public abstract class Character extends Entity {}

package player;

public class Player extends Character {}

I am getting the

The type Player cannot subclass the final class Character.

but I checked a million times and I am yet to use final all but ONCE in my project. What gives?

4

There are 4 answers

1
Adam Kotwasinski On BEST ANSWER

You are extending java.lang.Character (which does not need an import, as it comes from java.lang).

Insert import characters.Character into your Player code.


Reference: using package members:

For convenience, the Java compiler automatically imports two entire packages for each source file: (1) the java.lang package and (2) the current package (the package for the current file).

1
Chris On

Character is a class of java.lang (the wrapper class of "char"). you have to import characters.Character in your Player class

package player;
import characters.Character

public class Player extends Character {

}
0
Jabongg On

Character is a final class as defined in Java Docs:

public final class Character
extends Object
implements Serializable, Comparable<Character>

so it cannot be sub-classed.

You are getting error from this Character class, which is being implicitly imported. Beware!.

0
Andrew Tobilko On

In this case, I strongly recommend using the fully qualified name of the Character class in the extends clause.

public class Player extends characters.Character {}

Experienced Java developers know that java.lang.Character is final and can't thereby be extended. By writing class Player extends Character, you would probably make them nonplussed.

Every compilation unit implicitly imports every public type name declared in the predefined package java.lang, as if the declaration import java.lang.*; appeared at the beginning of each compilation unit immediately after any package declaration. As a result, the names of all those types are available as simple names in every compilation unit.

Java 11 Specification > 7. Packages and Modules > 7.3. Compilation Units

Of course, it would be more reasonable to pick up a name that doesn't collide with the classes from the standard java.lang package (like Person, or GameCharacter).