Java编写一个程序,展示无论创建某个特定类的多少对象,这个类的某个特定static成员变量只有一个属性。

首先看static关键字
static可以修饰属性和方法,与对象无关。
1.static修饰属性,称为静态属性(类属性),所有对象共享此属性值。静态属性一般通过类名称直接调用。
2.static修饰方法,称为类方法,直接通过类名称调用,与对象实例化无关。常用于工具方法。

*代码:
class Person
{ private String name;
private int age;
public static String country;

}
public class Mytest{
public static void main(String [] args){
Person person=new Person();
Person.country=“民国”;
Person person1=new Person();
Person.country=“中国”;
System.out.println(person.country);
System.out.println(person1.country);
}
}*

运行结果如下图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44149554/article/details/88184798