static关键字

1.static 可以用来修饰属性,方法,类
(1)修饰属性:如果一个类中的属性被static修饰,不管生成多少个该类的对象,它们共同使用同一个static变量

public class StaticSay
{
public static void main(String[] args)
{
StaticDemo sd = new StaticDemo();
StaticDemo sd1 = new StaticDemo();
sd.a=10;//可直接用类名.变量名调用
System.out.println(sd1.a);

}
}
class StaticDemo
{
static int a;
}
输出:10,而不是0;

(2)static修饰方法:static修饰的方法为静态方法。可以用类名.方法名调用;
静态方法是可以被继承下来的,但是不能被重写

public class StaticSay
{
public static void main(String[] args)
{
StaticDemo sd = new StaticDemo();
sd.method();
StaticDemo.method();

}
}
class StaticDemo
{
public static void method()
{
System.out.println("static method");
}
}

(3)静态代码块:先于构造方法执行,因为执行时将.class文件加载到JVM上时候就执行,而构造方法是在构造对象的时候执行。只执行一次静态代码块(因为只加载一次文件,嘿嘿)

class P
{
static
{
System.out.println("static block");
}
public P()
{
System.out.println("constructor block");
}
}

(4)不能在静态方法中访问非静态成员变量,可以在静态方法中访问非静态成员变量,可以静态方法中访问静态成员变量。(静态的只能访问静态,非静态可以访问一切);
不能在静态方法中使用this
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值