In Java classes, the usage of these three keywords is different. Let’s look at a table first:
private
Most member variables are modified to be private, and they are not expected to be accessed by any other external class. Can only be accessed by member functions inside the class.
default
It is designed for access to this package. Any classes, interfaces, exceptions, etc. under this package can access each other, even members of the parent class that are not modified with protected.
protected
The main function is to protect subclasses. Its meaning is that subclasses can use the members it modifies, but not others. It is equivalent to an inherited thing passed to subclasses
public
Needless to say, you can access it from anywhere
The code description is below.
packageone folder under src, Alpha.java
package packageone;
public class Alpha {
public void test() //By defining public member functions, instance access cannot be directly accessed to the outside world.
{
this.pub();
this.pro();
this.def();
this.pri();
}
public void pub() //Define public member function
{
System.out.println( "public");
}
protected void pro() //Define protected member function
{
System.out.println( "protected");
}
void def() //Define default member function
{
System.out.println( "default");
}
private void pri() //Define private member function
{
System.out.println( "private");
}
}
packageone folder under src, Beta.java
package packageone;
public class Beta {
public void test()
{
Alpha alpha = new Alpha();
alpha.pub();
alpha.pro();
alpha.def();
// alpha.pri(); //Error, cannot be accessed
}
}
packagetwo folder under src, AlphaSub.java
package packagetwo;
import packageone.Alpha;
public class AlphaSub extends Alpha {
public void test()
{
super.pub();
super.pro();
// super.def(); //Error, cannot write essay
// super.pri(); //Error, cannot write essay
}
}
Packagetwo folder under src, Gamma.java
package packagetwo;
import packageone.Alpha;
public class Gamma {
public void test()
{
Alpha alpha = new Alpha();
alpha.pub();
// alpha.pro(); //Error, cannot be accessed
// alpha.def(); //Error, cannot be accessed
// alpha.pri(); //Error, cannot be accessed
}
}
Main function Test.java
import packageone.Alpha;
public class Test {
public static void main(String[] args)
{
new Alpha().test();
}
}
Comparison summary:
- private can only be accessed in the class department; public can be accessed globally;
- The difference between protected and default is that default can only be accessed within the current package;