1.static 可以用来修饰属性,方法,类
(1)修饰属性:如果一个类中的属性被static修饰,不管生成多少个该类的对象,它们共同使用同一个static变量
(2)static修饰方法:static修饰的方法为静态方法。可以用类名.方法名调用;
静态方法是可以被继承下来的,但是不能被重写
(3)静态代码块:先于构造方法执行,因为执行时将.class文件加载到JVM上时候就执行,而构造方法是在构造对象的时候执行。只执行一次静态代码块(因为只加载一次文件,嘿嘿)
(4)不能在静态方法中访问非静态成员变量,可以在静态方法中访问非静态成员变量,可以静态方法中访问静态成员变量。(静态的只能访问静态,非静态可以访问一切);
不能在静态方法中使用this
(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
2127

被折叠的 条评论
为什么被折叠?



