JCKE
JCKE

Reputation: 394

Abstract inner class within non-abstract outer class

I have a super-class A with an abstract inner-class Inner, with another class B that extends A. Why doesn't A force B to implement the abstract inner-class?

I've already looked here, but it only specifies abstract methods in non-abstracts classes. Does the same principle apply here?

public class A {
    ...

    abstract class Inner {
        ...
    }
}

public class B extends A { 
    ...

    // Isn't forcing me to implement Inner
}

Upvotes: 0

Views: 264

Answers (4)

ajb
ajb

Reputation: 31699

If you define a new concrete class that extends an abstract class, it has to implement the methods. But you haven't defined a new concrete class that extends Inner. You've defined a new class B that extends A; in a sense, B inherits the Inner class, but it's still abstract. (You can say B.Inner in some contexts, but from my testing it appears that the compiler treats it the same as A.Inner.)

Upvotes: 0

user207421
user207421

Reputation: 310909

Because it would be a pointless restriction unless some code in B tried to instantiate A.Inner, in which case the existing rule would already catch it.

Upvotes: 0

Scruffy
Scruffy

Reputation: 580

In many situations, there is no need to implement A.Inner. I was recently working with a UI-free browser library for Java. They had a class Element with subclasses like Anchor, Input, Span, Script, Style. Surely you wouldn't want to be forced to implement, for example, all the subclasses of Element? This is particularly true when the superclass is a member of someone else's code. Said superclass may have private methods referring to private subclasses.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

An inner class, whether it's abstract or not, is basically syntactic sugar for a class that has a built-in reference to an instance of another class, its enclosing class. The fact that it is nested simply adds potential accessibility restrictions. Other than that, it's just like any other class (minus a few other restrictions on static members).

Upvotes: 1

Related Questions