赞
踩
static修饰符
1.
public class Test01 { public static void main(String[] args) { MyClass mc1 = new MyClass(); MyClass mc2 = new MyClass(); mc1.a = 100; mc1.b = 200; mc2.a = 300; mc2.b = 400; System.out.println(mc1.a); System.out.println(mc1.b); System.out.println(mc2.a); System.out.println(mc2.b); } } class MyClass{ static int a; int b; }
输出:
300
200
300
400
a是静态属性,是整个类共同持有的共享空间,任何对象修改,都会影响其他对象。
5 7
5报错是因为a是非静态属性,而m2方法是静态方法,静态方法无法访问非静态属性,所以无法访问到a
7报错是因为fa方法是非静态方法,而m2方法是静态方法,静态方法无法调用非静态方法,所以无法调用fa方法
public class Test03 {
public static void main(String[] args) {
MyClass mc1 = new MyClass();
MyClass mc2 = new MyClass();
MyClass mc3 = new MyClass();
}
}
class MyClass{
static int count = 0;
public MyClass() {
count++;
System.out.println(count);
}
}
输出:
1
2
3
public class Test04 { public static void main(String[] args) { MyClass mc1 = new MyClass(); System.out.println(mc1.i); MyClass mc2 = new MyClass(10); System.out.println(mc2.i); } } class MyClass{ static int i = 10; static { i = 20; System.out.println("In Static"); } public MyClass() { System.out.println("MyClass()"); } public MyClass(int i) { System.out.println("MyClass(int)"); this.i= i; } }
输出:
In Static
MyClass()
20
MyClass(int)
10
public class Test05 { public static void main(String[] args) { Super sup = new Sub(); sup.m1(); sup.m2(); Sub sub = (Sub)sup; sub.m1(); sub.m2(); } } class Super{ public static void m1(){ System.out.println("m1 in Super"); } public void m2() { System.out.println("m2 in Super"); } } class Sub extends Super{ public static void m1() { System.out.println("m1 in Sub"); } public void m2() { System.out.println("m2 in Sub"); } }
输出:
m1 in Super
m2 in Sub
m1 in Sub
m2 in Sub
ACDE
15.设计一个类MyClass,为MyClass增加一个count属性,用来统计总共创建了多少个对象。
public class Test15 {
}
class MyClass{
static int count = 0;
public MyClass() {
count++;
System.out.println(count);
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。