Home > Java > javaTutorial > Analysis of member access instances in java classes

Analysis of member access instances in java classes

PHPz
Release: 2023-05-02 22:01:05
forward
871 people have browsed it

1. Static members

Static members belong to classes and require class access when accessing.

The static member open space is opened when this type of memory is first loaded.

2. Non-static members

Non-static members belong to objects and need to be accessed using objects.

When the object is instantiated, non-static members open space.

In static methods, non-static members cannot be accessed directly.

Use non-static methods to directly access static members.

3. Example

class Person {
    String name;
    static int a;
    
    void eat() {}
    static void sleep() {}
}
class Program {
    public static void main(String[] args) {
        Person xiaoming = new Person();
        // 访问非静态成员
        xiaoming.name = "xiaoming";
        xiaoming.eat();
        // 访问静态成员
        Person.a = 10;
        Person.sleep();
        // 注:
        // 访问静态的成员, 也可以使用对象来访问, 但是会有警告
        // 推荐使用类来访问静态成员
    }
}
Copy after login

The above is the detailed content of Analysis of member access instances in java classes. 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