Search code examples
javainheritanceencapsulation

How can i make a method with call access only inside the child class?


I want to give a method an access that only the child classes and the current class can call. For example:

public class Parent{ 
something void mySetterMethod(int input){
     this.something = input;
   }
}

public class Child extends Parent{
     mySetterMethod(otherInput);
}

but this should not be able to work for:

public class SomeClassInSamePackage(){
    public static void main(String[] args){
       Parent parent = new Parent();
       parent.mySetterMethod(input);
}

Solution

  • As a general piece of advice prefer composition over inheritance.

    public class Parent { 
        public void mySetterMethod(int input){
         this.something = input;
       }
    }
    
    public class Child {
        private final Parent parent = new Parent();
        ...
            parent.mySetterMethod(otherInput);
        ...
    }
    

    You could just not call it from the same package.

    As a historical note, Java 1.0 had private protected, although apparently it was buggy.