-
什么是this?
java 虚拟机会给每个对象分配this,代表当前对象。
class Dog
{String name;int age;public Dog(){}public Dog(String name,int age){this.name = name; //this.表示当前属性的namethis.age = age; // this.表示当前属性的age}
}
public class test8
{public static void main(String[] args){Dog dog1 = new Dog("脑袋大",3);
System.out.println("dog1的结果:" + dog1.name + "," + dog1.age);}
}
-
为什么说this就代表new出的对象呢?
因为在创建对象的时候,其实this就已经有了只不过this是隐藏起来的。在Java中我们是不能输出对象的内部地址的,但是我们可以用hashcode()函数去当作一个对象的地址,hashcode()返回的是一个整数。
-
this需要注意的细节:
-
this关键字可以用来访问本类的属性、方法、构造器
-
this用于区分当前类的属性和局部变量
-
代码片段:
-
class Dog {String name = "脑袋大";int age = 3;public Dog(){}public Dog(String name,int age){this.name = name;this.age = age;} public void f1(){String name = "小米";int age = 2;System.out.println("我是方法f1()..................");System.out.println("不加this关键字的name和age:" + name + "," + age);System.out.println("加this关键字的this.name和this.age:" + this.name + "," + this.age);} public void f2(){System.out.println("我是方法f2()..................");} }
输出:
我是方法f1()..................
不加this关键字的name和age:小米,2
加this关键字的this.name和this.age:脑袋大,3
-
-
- 访问成员方法的语法: this.方法名(参数列表)
-
代码片段:
class Dog {String name = "脑袋大";int age = 3;public Dog(){}public Dog(String name,int age){this.name = name;this.age = age;} public void f1(){String name = "小米";int age = 2;System.out.println("我是方法f1()..................");// System.out.println("不加this关键字的name和age:" + name + "," + age);// System.out.println("加this关键字的this.name和this.age:" // + this.name + "," + this.age);} public void f2(){// 两个方法// 第一种f1();System.out.println("我是方法f2()..................");// 第二种this.f1();} }
输出: 我是方法f1().................. 我是方法f2().................. 我是方法f1()..................
-
访问构造器语法:this(参数列表);注意只能在构造器中使用(即只能在构造器中访问另一个构造器,且必须放在构造器方法体的第一句话)
-
代码片段:
class Dog {String name = "脑袋大";int age = 3;public Dog(){// 必须要写在语句的第一句话this("小狗",1);System.out.println("我是无参构造器..................");}public Dog(String name,int age){this.name = name;this.age = age;System.out.println("我是有参构造器:" + this.name + "," + this.age);} }
输出: 我是有参构造器:小狗,1 我是无参构造器..................
-
-
this不能再类定义的外部使用,只能在类定义的方法中使用。
-
this小结:简单的说,哪个对象调用,this就代表哪个对象。