JavaSE学习之常见易错点总结--第一期

 💕"不要同情自己,那是卑劣懦夫干的勾当。"💕

作者:Mylvzi 

 文章主要内容:Java学习之常见易错点总结--第一期 

1.什么时候变量不用初始化?

  先来看如下代码:

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
    }

2. 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中可以通过对象名访问类变量(但是不建议)

 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.牢记一句话:“静态的就是类的”

5.toString方法的改写

  在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方法
}

6. Import是导入指定包的类!

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值