inner class extending
Asked Answered
B

4

14

In java, say I have the following class:

public class A{
  protected class B{
  }
}

can I extend the inner class by doing the following?

public class C extends A{
  protected class D extends B{
  }
}

What I want to do is that I have the class C above and I need to change something in A's inner class so I was thinking that I need to extend the inner class to do so but I wasn't sure how exactly to do that.

Bujumbura answered 26/2, 2012 at 23:1 Comment(1)
Yes you can extend the inner class like that.Foofaraw
C
7

According to this page, you have the right way figured out to extend inner classes. A few tips about it can be found here, in the middle of the article (search for "extend").

Cecilacecile answered 26/2, 2012 at 23:7 Comment(0)
C
1

If that doesn't work (I don't think it will), the following should:

public class C extends A{
  protected class D extends A.B{
  }
}

Well, it will, but what if you have another class named B outside of A?

Edit: nope, it makes no difference. Even if there is another class named B, it will still take A.B. So your syntax is correct.

Clouet answered 26/2, 2012 at 23:5 Comment(1)
It wouldn't work if D was static, but it's not, so it does.Sheelah
C
1

You are allowed to do that but don't expect your C class to use D class instead of A's inner B class automatically.

Cassatt answered 26/2, 2012 at 23:30 Comment(2)
This is the truly crucial aspect with inheritance of outer/inner class data structures. Is there any known pattern to deal with this problem (generics etc.)?Kursk
I'd say inject the actual instance of B (B or D in this case) you want to use.Cassatt
S
0

Each inner class can independently inherit from an implementation. Thus, the inner class is not limited by whether the outer class is already inheriting from an implementation.

--- Thinking In Java

Shaffert answered 30/8, 2018 at 19:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.