For beginners, considering this example can be helpful;
Consider I have developed MyClass in the foo package and it has a fantastic method named print which you are interested in calling it ( itit could be a method or property ):
package foo; // I am in foo public class MyClass { private void print() { //This is private System.out.println("I can print!"); } } package bar; \\You are not in same package as me import foo.MyClass; public class YourClass { void test() { MyClass myClass = new MyClass(); myClass.print(); } } package foo; public class MyClass { void print() { // No access modifier means default or package-private System.out.println("I can print!"); } } NoNow consider this: Again you come to me
- You: My boss told me I can not change my package ( Inin the actual world, you can not change youyour package to use other classes methods)
- Me : There is another way, if you
extendme and I makeprint()protected, then you can use it whether you change you package or not. ( So sub classingSo subclassing will always give you access to my method).
package foo; protected class MyClass { // itIt is now protected protected void print() { System.out.println("I can print!"); } } Here is YourClass:
package bar; // You are on your own package import foo.MyClass; public class YourClass extends MyClass { void test() { // You initiate yourself! But as you extend me, you can call my print() YourClass yourClass = new YourClass(); yourClass.print(); } } You may have noticed that by making a method protected allall other classes can use it by extending it, and you can not easily control how can use it can be used. This was solved in java 17Java 17 by introducing sealed and permits words. So you can define which classes can extend you. By something like public sealed class MyClass permits YourClass See What are sealed classes in Java 17?What are sealed classes in Java 17? for more infoinformation.