4

A class can be a "subclass" of itself if its inner class extend the outer class so the class is somehow extending itself without throwing any Exception. So, does it really mean a class is also a subclass of itself?

Thanks.

Schildmeijer
  • 20,702
  • 12
  • 62
  • 79
Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74

6 Answers6

7

A class is not a subclass of itself. An inner class could be a subclass of some other class, but that is a separate class. You can verify this by comparing the Class instances you get when you call getClass().

Mr. Shiny and New 安宇
  • 13,822
  • 6
  • 44
  • 64
3

The definition of subclass is that it extends another class and inherits the state and behaviors from that class. A class cannot extend itself since it IS itself, so it is not a subclass. Inner classes are allowed to extend the outer class because those are two different classes.

z -
  • 7,130
  • 3
  • 40
  • 68
3
public class ParentClass {

    int intField = 10;

    class InnerClass extends ParentClass {

    }

    public static void main(String... args) {
        ParentClass parentClass = new ParentClass();
        InnerClass innerClass = parentClass.new InnerClass();

        System.out.println(innerClass.intField);

        InnerClass innerClass2 = innerClass.new InnerClass();
    }
}
setzamora
  • 3,560
  • 6
  • 34
  • 48
2

Actually JVM doesn't now anything about inner classes.

All inner classes become usual classes after compilation but compiler gives them accessors to all fields of outer class.

In OOP theory, class cannot be its subclass or superclass.

Roman
  • 64,384
  • 92
  • 238
  • 332
  • Note entirely true. It is flagged in the bytecode format. As an example: http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getEnclosingClass() – Tom Hawtin - tackline May 08 '09 at 13:40
  • True, there is metadata added so that it can be expected by the reflection library. However, the class format itself does not have any special handling of inner classes. They are just ordinary classes that happen to have funny names and some extra metadata. – Antimony Jun 30 '12 at 14:10
1

No. An inner class is something completely different from its outer class. Unless I am misunderstanding your question...

Adam Paynter
  • 46,244
  • 33
  • 149
  • 164
0

If you define a class subclassing itself as this:

public class Test {

    public static void main(String[] args) {
        // whatever...
    }

    class TestChild extends Test {
        // whatever...
    }
}

Then yes this is possible. But note that these are two entirely separate classes, barring the fact the one is inner to the other.

Yuval Adam
  • 161,610
  • 92
  • 305
  • 395