乐猿 2021-01-31 17:46 采纳率: 0%
浏览 9

为什么要用static修饰 a才能自增。

package day20;

public class Demo1 {
    public static void main(String[] args) {
        Person p1 = new Person("小乐",15);
        Person p2 = new Person("小花",16);
        Person p3 = new Person("小明",17);
        Person p4 = new Person("小王",18);
        Person p5 = new Person("小丽",19);
        p1.say();
        p2.say();
        p3.say();
        p4.say();
        p5.say();
    }
}
class Person{
    private String name;
    private int age;
    static int a = 1;
    Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    void say(){
        System.out.println("序号:("+a+++") 我叫"+name+",我今年"+age+"岁了。");
    }
}
  • 写回答

1条回答 默认 最新

  • 小码上线 2021-01-31 19:42
    关注

    static修饰的变量,是类变量。属于类。每new一次,这个变量,就作一次++

    no-static的变量,是对象私有的。属于对象 。单独属于,每个对象。不作++

    评论

报告相同问题?