Java学习——static关键字

Java中的static关键字


1.static属性:用static修饰的属性,也叫类属性,通过类名调用(区别于通过对象调用)

类属性强调的是一种共享属性,比如有一个ChinaPerson的类,其中每个人都是一个对象,有不同的名字、年龄等,但是他们属于的国家都是中国,这里这个中国就是一个共享属性。我们可以将国家这个属性设置为static属性,值为“中国”,这样我们创建对象时就不用给每个对象设置国家这个属性的值了。

这里还有一个问题,当我们在ChinaPerson类中直接将country属性设置为“中国”不就行了吗?

对于这个问题,假设我们有一天在ChinaPerson类不能改动的情况下,想把“中国”改为“中华人民共和国”怎么办呢?

我们需要给每一个对象的country重新赋值,当对象很多的情况时,实现起来非常麻烦。

怎么样才能把这个共享属性更只改一次就可以了呢?那就是加上static关键字。

class ChinaPerson{
    public String name;
    public static String country = "中国";
    public ChinaPerson(String name){
        this.name = name;
    }
    public void Info(){
        System.out.println("name is "+this.name+"country is "+country);
    }
}
public class Test{
    public static void main(String[] args) {
        ChinaPerson person1 = new ChinaPerson("张三");
        ChinaPerson person2 = new ChinaPerson("张三");
        ChinaPerson.country = "中华人民共和国";
        person1.Info();
        person2.Info();
    }
}

当我们把一个属性用static关键字修饰,系统把这个属性放在了全局数据区,每个对象的country都指向这个区域,通过一个对象上修改这个值,对其他对象都有影响。

static关键字特点:

访问static属性应该用类名称. 属性名

所有的非static属性(实例属性--与对象强相关)必须在类实例化后使用,而static属性(类属性)不受对象实例化控制,即没有对象也可以用。

2.static方法(类方法、静态方法)

既然有static属性,也有static方法。

static方法与对象实例化无关,通过类名直接调用,常见于工具类方法。我们常见的有:
Arrays.sort();
system.arraycopy();
...

class ChinaPerson{
    public String name;
    public static String country;
    public ChinaPerson(String name){
        this.name = name;
    }
    public static void setCountyt(String c){
        country = c;
    }
}
public class Test{
    public static void main(String[] args) {
        ChinaPerson person1 = new ChinaPerson("张三");
        ChinaPerson.setCountyt("中华人民共和国");
        System.out.println("name is "+person1.name+"  country is "+ChinaPerson.country);
    }
}

注意:

static方法不能访问类中的普通属性 (  普通属性和对象强相关而static方法和对象无关);
static方法可以访问类中的static属性;
普通方法可以访问类中static属性和普通属性;

外部类不能用static修饰;
内部类可以用static修饰;

使用static定义方法只有一个目的:某些方法不希望受到类的控制,即可以在没有实例化对象的时候执行(广泛存在
于工具类中)

猜你喜欢

转载自blog.csdn.net/eve8888888/article/details/83181670