在Java的使用过程中this和super 方法会使调用对象中的属性和父类的方法和属性更加清晰
public class Student { private String name = "Your Name"; public void setName(String name) { this.name = name;//调用当前属性 } public String getName() { this.setName("Tom");//调用当前方法 return this.name; } public Student getStudent() { return this;//表示该对象 } public static void main(String[] args) { Student student = new Student(); System.out.println(student.name); System.out.println(student.getStudent().name); System.out.println(student.getName()); System.out.println(student.getStudent().name); } }
输出为
Your Name
Your Name
Tom
Tom
可将this理解为一种指针指代当前对象,是对当前对象的一种引用。如果省略this,因为形参和属性崇明,在例子中的对象中name属性不会发生改变
省略this的输出:
Your Name
Your Name
Your Name
Your Name
重名问题解决后输出改变:
Your Name
Your Name
Tom
Tom
public class Student { protected String name = "Your Name"; public void setName(String n) { name = n; System.out.println("Call parent method"); } Student() { System.out.println("Father "); } Student(String name) { System.out.println("Father " + name); } }
public class StudentTom extends Student { public void setName(String name) { this.name = name; System.out.println("Call subclass method"); } StudentTom() { super(); } StudentTom(String fatherName) { super("Tom"); System.out.println(fatherName); } public static void main(String[] args) { StudentTom studentTom = new StudentTom(); System.out.println(studentTom.name); studentTom.setName("Tom"); System.out.println(studentTom.name); studentTom = new StudentTom(); studentTom = new StudentTom("this Tom"); } }
输出:
Father
Your Name
Call subclass method
Tom
Father
Father Tom
this Tom
super只能在子类的方法中使用,否则会无法从静态上下文中引用非静态 变量 super,报错。因为父类没有进行对象实例化。
原文:https://www.cnblogs.com/yus-1994/p/12914093.html