I’m curious if it’s possible to declare a member of a class such that it not be exposed to the derived class either at all, or at least until the subclass calls super()
. Is there such a feature in Java?
class A{ static int foo = 1; } class B extends A{ public B(){ System.out.print(foo);/// how do I make this not work? } }
Edit: I actually typed my question with the solution, by accident (my actual code was missing the private). So I’ll edit my question and remove the private so that it’s a meaningful question 🙂
Answer
That already won’t work – the member is private, so isn’t visible from B.
However, if you’re trying to hide an already-visible member in a subclass, e.g.
public class A { public void foo() { // Whatever } } public class B extends A { // ??? } ... B b = new B(); b.foo(); // I don't want this to work, because it's a B!
… then you can’t do that. It would break Liskov’s Substitution Principle.