1. Any other class can access classes, methods, constructors and interfaces declared as public.
2. If the public classes that access each other are distributed in different packages, you need to import the package where the corresponding public class is located. Due to class inheritance, all public methods and variables can be inherited by its subclasses.
Example
public class demo1{ public static void main(String[] args) { Person p1 = new Person(); p1.fn(); System.out.println(p1.a); // 100 System.out.println(p1.scorce); // 12.5 // System.out.println(p1.abc); // 无法访问 报错 } } class Person{ int a = 100; // 在同一包内可见,不使用任何修饰符。 public float scorce = 12.5f; // 对所有类可见。使用对象:类、接口、变量、方法 private double abv = 545.6487485; // 在同一类内可见。 public void fn(){ System.out.println("我是fn函数"); } }
The above is the detailed content of How to use the public modifier in java. For more information, please follow other related articles on the PHP Chinese website!