Reputation: 3
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);
}
Upvotes: 0
Views: 741
Reputation: 147124
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.
Upvotes: 2