Architecture question.
If you need to get something from the child class, you will write an abstract function, like

abstract class Parent{

private void something(){
String x = getChildName();

abstract String getChildName()


Every child class would have to implement getChildName() and return a string, which would be used when parent's function is called.

But what if
We need to get something from the child class, and not allow child class to use that function on its own?
foe eg if there is a child class of Parent say

Class Box extends Parent{

public String getChildName(){
return "BoxxyBox";

public void makeBabyBoxes(){
String s3 = getChildName()+"GG" ; //WRONG
// should have called some parent function or variable to get this value


as in example, there's no one stopping the child function from using its own function directly, therby making the parent go all waste(in my case) So what is the solution to this? to take some value from the chill class without letting it use directly?

I currently have an approach that uses effectively final variables and list to achieve something like this, but that's not so elegant. would love to hear your take on this

  • 0
    Can't do this in Java. C++, however, has private virtuals for exactly what you're talking about. One of the few languages I know that does it.

    If the child class's private abstract implementation doesnt need anything from the instance (e.g. it's a pure function) then consider passing an anonymous interface implementation to the parent via the constructor.

    A word of caution, however: that's some major code smell. You might want to consider the overall design if you're running into this particular use case.
  • 0
    @junon actually the child classes have the power to create certain objects that are tied to the lifecycle of a system. I don't want the child classes to handle those variables because they might fuck up the lifecycle and cause memory leaks. So i am keeping copies of those variables in the base class and handling the lifecycle there only. that's why i needed that.

    Additionally i have this approach to make that abstract function as a void with effectively final list:

    abstract class Parent{

    private void something(){
    val list = new List()

    String s = list.get(0);

    abstract void putChildName(List<String> list)


    when the child class extends this, they will be adding their string(or any other object) to the list provided by the parent.
    this is making me get what i want but its not much elegant. it looks like a hack and i wana go through some usual routes of getting/setting data ^_^!
Add Comment