static关键字的作用?

Java Language Specification, 3rd 写道

8.4.3.2 static Methods

A method that is declared static is called a class method. A class method is always invoked without reference to a particular object. An attempt to reference the current object using the keyword this or the keyword super or to reference the type parameters of any surrounding declaration in the body of a class method results in a compile-time error. It is a compile-time error for a static method to be declared abstract.

A method that is not declared static is called an instance method, and sometimes called a non-static method. An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.

15.8.3 this

The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.

static修饰的变量和方法是独立于对象而存在的,不产生副本,可以直接用类名来调用。

一.static修饰的变量

static修饰的变量当且仅当类被加载时初始化。而非static变量在实例化对象时被初始化,产生多个副本,多个对象不互相影响。

局部变量不能被static修饰

static不改变变量和方法的作用域,其作用域只受四个访问修饰符的影响

二.static修饰的方法

被static修饰的方法内部不能调用非static的变量和方法,非static方法内部可以调用static变量的方法和变量。

三.static修饰的代码块

static修饰的代码块在且只在类被加载时执行一次。

执行顺序:static代码块优于构造块,优于构造方法。

总结

  1. static class, 声明静态内部类;
  2. static field, 声明静态成员变量;
  3. static method, 声明静态成员方法;
  4. static {...}, 声明静态代码块;
  5. import static package, 声明静态成员变量可见.

转载于:https://my.oschina.net/u/3672057/blog/1536669

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值