0

if I have an abstract Parent class which has a templateMethod and a concrete Child class :

abstract class Parent
{
    final void templateMethod()
    {
        foo();
    }

    abstract void foo();
}

class Child extends Parent
{
    @Override
    void foo()
    {
        System.out.println("foo");
    }
}

what should i do if i only want the user to know that templateMethod and do not want to expose foo method to class Child's user while let the Child class define the implementation of foo method ? Or, is template method not suitable in this case? Then, is there any other strategies i can use?

Happy-Monad
  • 1,962
  • 1
  • 6
  • 13
zan qwq
  • 1
  • 3
  • 1
    Make the templateMethod() public, but the foo() method protected. https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – JB Nizet Dec 02 '19 at 07:31

1 Answers1

0

As suggested by JB Nizet in the comment, you could do:

abstract class Parent {
    final void templateMethod() {
        foo();
    }

    abstract protected void foo();
}

class Child extends Parent {
    @Override
    protected void foo() {
        System.out.println("foo");
    }
}

Since Parent.foo() is protected, only subclasses of Parent can call the method.

You might also find this question helpful: What is the difference between public, protected, package-private and private in Java?

armandino
  • 17,625
  • 17
  • 69
  • 81