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

Analysis of member access instances in java classes

PHPz
PHPzforward
2023-05-02 22:01:05852browse

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();
        // 注:
        // 访问静态的成员, 也可以使用对象来访问, 但是会有警告
        // 推荐使用类来访问静态成员
    }
}

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete