public class Test {
// s作成员变量,会被赋默认值
public static String s;
public static void main(String[] args) {
System.out.println(Test.s);// 打印:null
}
}
java复制代码
public static boolean a;
public static void main(String[] args) {
System.out.println(a);// 输出false
}
2. Java中不存在静态的局部变量,只有静态成员变量!
判断如下代码能否进行:
java复制代码
public class Test {
public int aMethod(){
static int i = 0;
i++;
return i;
}
public static void main(String args[]){
Test test = new Test();
test.aMethod();
int j = test.aMethod();
System.out.println(j);
}
}// 编译失败
分析:
3. 再次强调Java是一种强类型语言,对类型有着严格的区分
4.Java中可以通过对象名访问类变量(但是不建议)
java复制代码
public class HasStatic {// 1
private static int x = 100;// 2
public static void main(String args[]) {// 3
HasStatic hsl = new HasStatic();// 4
hsl.x++;// 5
HasStatic hs2 = new HasStatic();// 6
hs2.x++;// 7
hsl = new HasStatic();// 8
hsl.x++;// 9
HasStatic.x--;// 10
System.out.println(" x=" + x);// 11
}
}
再来看一个代码(易错)
java复制代码
package NowCoder;
class Test {
public static void hello() {
System.out.println("hello");
}
}
public class MyApplication {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test=null;
test.hello();// 编译成功 打印hello
}
}
public void println(Object x) {
StringBuffer sb = new StringBuffer();
sb.append(x);
System.out.print(sb.toString());// 调用toString方法
System.out.flush();
}
题目:
java复制代码
class Test{
public String toString() {
System.out.print("aaa");
return "bbb";
}
}
public static void main(String[] args) {
Test test = new Test();
System.out.println(test);
// 输出aaabbb
// 会调用上面你自己写的toString方法
}