除了静态代码块之外,还有实例代码块。
语法:
{
java语句;
java语句;
}
实例代码块在构造方法执行之前执行,构造方法每执行一次,实例代码块就会被提前执行一次。
这几天都没有去看视频敲代码 所以博客进度很慢 但回头看好像自己也没有做什么事 还是效率太低了
this关键字
public class this01 {
private int id;
private String name;
public this01 (int id,String name)
{
id = id;
name = name;
}
public static void main(String[] args){
this01 x = new this01(180 ,"tx");
this01 y = new this01(160 ,"xy");
System.out.println(x);
System.out.println(y);
}
public String toString() {
return "id = " + id + " name = " + name;
}
}
-------------------------------------------------------
id = 0 name = null
id = 0 name = null
发现成员变量传不进值 ,是默认初始值
就近原则不会给成员变量赋值
public class this01 {
private int id;
private String name;
public this01 (int id,String name)
{
this.id = id;
//右边的id指的是构造方法中传入的id
// 左边的id指的是成员属性中的id
this.name = name;
}
public static void main(String[] args){
this01 x = new this01(180 ,"tx");
this01 y = new this01(160 ,"xy");
System.out.println(x);
System.out.println(y);
}
public String toString() {
return "id = " + id + " name = " + name;
}
}
----------------------------------------------
id = 180 name = tx
id = 160 name = xy
而加上this关键字后 ,就指向了当前的成员变量
使用this区分成员变量和局部变量
不管是成员方法也好,还是成员属性也好,他们都是成员的
x.print();是"引用.",引用x他不是对象,它没有成员方法和成员属性的。它只是对象的别名而已。所以叫引用。
x调用一个成员方法的时候,实际上是x所指向的这个对象在调用print()。
每个成员方法中都有一个隐含的this参数,这个参数用来接收调用它的对象的this引用的值。
x是对象的引用,我们说成员方法是谁的?对象的
对象去调成员方法,对象在堆内存中,不在栈中。
所以调用方法的时候,真正的出发点肯定不是从栈里面出发的,而是从堆里面出发的。
堆里面唯一可能的出发点就是this。this就是这个对象本身。
静态方法和成员方法最大的区别在于,静态方法中没有隐含的this参数。
成员方法中有隐含的this参数。
这样也就解释了,为什么空指针异常发生在调用成员方法时,不会再静态方法被调用的时候发生。
每个成员方法和成员变量都带有一个this,这个this绝大部分情况下可以被省略,做区分的时候可以写出来。
public class this01 {
private int id;
private String name;
public this01 (int id,String name)
{
this.id = id;
this.name = name;
}
public void print() {
System.out.println("hello!!!!!!!!");
}
public void test() {
this.print();
}
public static void main(String[] args){
this01 x = new this01(180 ,"tx");
this01 y = new this01(160 ,"xy");
x.test();
y.test();
}
public String toString() {
return "id = " + id + " name = " + name;
}
}
---------------------------------------------------------
hello!!!!!!!!
hello!!!!!!!!