bin
bin

Reputation: 143

Restricting child class from accessing parent class method

Say I have an interface I and classes A and B.

interface I
{
  method();
}

class A implements I
{
  method()
  { //Implementation 1
  }
}

class B extends A
{
  method()
  { //Implementation 2
  }
}

I want to restrict B from accessing 'method'. A call to b.method() should always use a.method() instead of b.method implementation where a and b are instances of A and B respectively. Is there any workaround?

Wish interfaces supported another access modifier to handle such cases.

Upvotes: 2

Views: 1318

Answers (2)

SeniorJD
SeniorJD

Reputation: 7202

You can implement B like this:

class B extends A
{
  method()
  {
    method(true);
  }

  method(boolean callSuper)
  {
    if (callSuper)
    {
      super.method();
    } else {
      method_impl();
  }

  method_impl()
  {
    //Implementation method of B class
  }
}

Upvotes: 0

JonK
JonK

Reputation: 2108

As stealthjong alluded to in their comment, you can achieve this by making A's implementation of method() final:

interface I {
    public void method();
}

class A implements I {
    public final void method() {
        System.out.println("Hello World!");
    }
}

class B extends A { }

Because A applied the final modifier to the implementation of method(), B cannot then redefine it and will instead always call the version that it inherits from A.

If I were to write:

B instance = new B();
instance.method();

I would see the output "Hello World!".

Upvotes: 7

Related Questions