this是指向自身的一个对象,代表对象本身。
三种用法:
class Person { private int age = 10; public Person(){ System.out.println("初始化年龄:"+age); } public int GetAge(int age){ this.age = age; return this.age; } }
指向当前对象的父类,可以用super.xxx来引用父类的成员
class Person { String name; public void value() { this.name = "tom"; } } class Student extends Person { String name; public void value() { name = "jack"; super.value(); System.out.println(name); System.out.println(super.name); } } public class studySuperAndThis{ public static void main(String[] args) { Student student = new Student(); student.value(); } }
class Person { public static void prt(String s) { System.out.println(s); } Person() { prt("父类·无参数构造方法: " + "A Person."); }//构造方法(1) Person(String name) { prt("父类·含一个参数的构造方法: " + "A person's name is " + name); }//构造方法(2) } class Chinese extends Person { Chinese() { super(); // 调用父类构造方法(1) prt("子类·调用父类“无参数构造方法”: " + "A chinese coder."); } Chinese(String name) { super(name);// 调用父类具有相同形参的构造方法(2) prt("子类·调用父类”含一个参数的构造方法“: " + "his name is " + name); } Chinese(String name, int age) { this(name);// 调用具有相同形参的构造方法(3) prt("子类:调用子类具有相同形参的构造方法:his age is " + age); } }
注意: