Home > Java > javaTutorial > How to use the public modifier in java

How to use the public modifier in java

WBOY
Release: 2023-04-18 18:04:03
forward
1424 people have browsed it

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函数");
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template