💕"不要同情自己,那是卑劣懦夫干的勾当。"💕
作者:Mylvzi
文章主要内容:Java学习之常见易错点总结--第一期
先来看如下代码:
- public static void main(String[] args){
-
- String s;
-
- System.out.println("s="+s);// 会输出结果吗?
-
- }
![]()
显然这段代码无法通过编译,原因在于s是写在方法(函数)之内的,是局部变量,而局部变量必须进行初始化才能够使用!
但是,有同学可能模模糊糊有印象说:好像有时候变量不初始化也能通过编译,会自动给变量赋默认值啊。是的,有这种情况,这种变量只能是“成员变量”
- public class Test {
- // s作成员变量,会被赋默认值
- public static String s;
-
- public static void main(String[] args) {
- System.out.println(Test.s);// 打印:null
- }
- }
- public static boolean a;
-
- public static void main(String[] args) {
- System.out.println(a);// 输出false
- }

判断如下代码能否进行:
- 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);
- }
- }// 编译失败
分析:


- 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
- }
- }
再来看一个代码(易错)
- 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
- }
- }
test引用被赋值为null,表示不指向任何对象,所以可以使用对象名来访问静态方法
总结:
1.可以通过对象名来访问静态变量(但是不建议)
2.类变量是所有对象共享的,存在于方法区。只有一份!无论是通过类访问还是对象名访问,都是对同一份变量进行操作!
3.牢记一句话:“静态的就是类的”
在Java中println方法执行的过程中会自动调用一个方法-->toString,这个方法属于对象!也就是在执行println方法的过程中,编译器会从成员方法中寻找toString方法(平常只是隐藏了起来),如果你在成员方法中重写了一个toString方法,则println会执行你写的toString方法
源码:
- public void println(Object x) {
- StringBuffer sb = new StringBuffer();
- sb.append(x);
- System.out.print(sb.toString());// 调用toString方法
- System.out.flush();
- }
题目:
- 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方法
- }
