I just found a curious case.
class SomeClass {
abstract static class AbstractNested
extends SomeClass {
}
static class Sibling1
extends AbstractNested {
}
static class Sibling2
extends AbstractNested {
}
void a() {
new Sibling1.Sibling2(); // @@?
}
}
Why on earth does new Sibling1.Sibling2();
work? How can I make it doesn't?
CodePudding user response:
Sibling1
and Sibling2
aren't just siblings; they both extend the outer class (indirectly, via AbstractNested
), and so they inherit the nested class members.
CodePudding user response:
As Boann's answer,the reason is that both Sibling1
and Sibling2
are extends from AbstractNested
,and AbstractNested
are extends from SomeClass
, so they are all subclass of SomeClass
If you remove extends
from Someclass
or Sibling1
it will not compile
Case 1:
class SomeClass {
abstract static class AbstractNested
extends SomeClass {
}
static class Sibling1 {
}
static class Sibling2
extends AbstractNested {
}
void a() {
new Sibling1.Sibling2(); // will not compile
}
}
Case 2:
class SomeClass {
abstract static class AbstractNested {
}
static class Sibling1
extends AbstractNested {
}
static class Sibling2
extends AbstractNested {
}
void a() {
new Sibling1.Sibling2(); // will not compile
}
}