is there a way to hide a member of a Superclass from the derived class? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of is there a way to hide a member of a Superclass from the derived class? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about is there a way to hide a member of a Superclass from the derived class? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji