java基础(四)之this的使用
作用:
1、使用this调用成员变量和成员函数
2、使用this调用构造函数
Person.java:
class Person{ String name; //成员变量 void talk(String name){ //String name 形参 System.out.println("My name is " + this.name); } }
TestThis.java:
public class TestThis{ public static void main(String[] args){ Person p1 = new Person(); p1.name = "zhangsan"; p1.talk("lisi"); } }
输出结果:zhangsan
修改Person.java:
class Person{ String name; void talk(String name){ System.out.println("My name is " + name); } }
输出结果:lisi
使用this调用构造函数
Person.java
class Person{ String name; int age; String address; Person(){ System.out.println("test0"); } Person(String name,int age){ this(); this.name = name; this.age = age; System.out.println("test2"); } Person(String name,int age,String address){ this(name,age); System.out.println("test3"); } }
TestThis.java:
public class TestThis{ public static void main(String[] args){ Person p1 = new Person("boy",11,"china"); } }
输出结果如下: