可以用于修饰属性,方法和类(类 在后面的课程讲)。
如果一个成员变量是static的,那么我们可以通过 类名.成员变量名 的方式来使用它(推荐使用这种方式)
public class StaticTest {
public static void main(String[] args) {
/*MyStatic myStatic = new MyStaitc();
MyStaitc mystatic2 = new MyStatic();
mystatic.a = 10;
System.out.println(mystatic2);
*/
MyStatic myStatic = new MyStaitc();
MyStatic.a = 10;
System.out.println(myStaitc.a);
}
}
class MyStatic {
//int a 结果为0
static int a;//结果为10
}
static修饰方法:static 修饰的方法叫做静态方法。
public class StaticTest {
public static void main(String[] args) {
/*MyStatic test = new MyStatic();
test.output();
*/
MyStatic.output();//方法用了static来修饰,就可以直接用类名.方法名来调用。
}
}
class MyStatic {
public static void output() {
System.out.println("output");
}
}
对于静态方法来说,可以使用类名.方法名的方式来访问。
public class StaticTest {
public static void main(String[] args) {
N n = new N();
n.output();//输出为n
M m = new N();
m.output();//输出为m
}
}
class M {
public static void output() {
System.out.prkntln("m");
}
}
class N extends M{
public static void output() {
System.out.println("n");
}
}
静态方法只能继承,不能重写(Override)
public class StaticTest {
public static void main(String[] args) {
N n = new N();
n.output();//输出为m
}
}
class M {
public static void output() {
System.out.prkntln("m");
}
}
class N extends M{
}