举例讲解Java编程中this关键字与super关键字的用法

时间:2021-05-19

this
总要有个事物来代表类的当前对象,就像C++中的this指针一样,Java中的this关键字就是代表当前对象的引用。
它有三个主要的作用:
1、在构造方法中调用其他构造方法。
比如有一个Student类,有三个构造函数,某一个构造函数中调用另外构造函数,就要用到this(),而直接使用Student()是不可以的。
2、返回当前对象的引用。
3、区分成员变量名和参数名。
看下面的例子:

public class Student { private String name; private int age; private String college; public Student() { age = 20; } public Student(String name) { this();//can not be call Student,only use this() method. this.name = name; System.out.println("this student name is "+name); } public Student(String name,String college) { this(name);//C++中可以直接用Student(name)调用其他构造函数 this.college = college; System.out.println("this student name is "+name+" college is "+college); } public Student upgrade() { age++; return this; } public void print() { System.out.println("name is: "+name +" age is: "+age +" college is: "+college); } public static void main(String[] args) { Student student1 = new Student("linc"); Student student2 = new Student("linc","shenyang college"); student2.upgrade().print(); } }

迷失在茫茫的对象海洋时,不要忘了用this来找到自我。

super
super是this的父辈。从面相对象的角度说,这两个概念是很好理解的。
子类从父类继承过来,父类的protected及以上的属性和方法在子类中是天生就具有的。那么,为什么还要有super这个关键字?
第一、看父类的构造
子类构造时要先调用父类的默认构造函数的,这与C++的构造属性一致。当父类有多个构造函数时,你需要指定调用哪个。这是就需要使用super(arg1,arg2...)。
需要注意的是,在子类的构造函数中调用基类的构造函数时,必须要把super写作最前面,否则报错。
第二,在子类覆盖父类的一些方法中再调用父类的此方法。大家都知道,在子类中覆盖父类的一些方法是面向对象中多态的一种方式,而因为其他种种原因,需要在此方法中调用父类的此方法,用以区分,此时需要使用super来完成。

public class ClassLeader extends Student { private String duty; public ClassLeader() { duty = "class monitor"; } public ClassLeader(String duty,String name,String college) { super(name,college); this.duty = duty; } public void print() { super.print(); System.out.println("duty is " + duty); } public static void main(String[] args) { ClassLeader leader = new ClassLeader("life","linc","shenyang"); leader.print(); } }

将两个类文件放在同一个目录,编译并运行:

D:\workspace\Java\project261\super>javac -d . *java D:\workspace\Java\project261\super>java ClassLeader

运行结果:

this student name is linc this student name is linc college is shenyang name is: linc age is: 20 college is: shenyang duty is life

看看在其他语言中是怎样来处理的:
C#中提供了base关键字来完成super相似的功能,C++直接用基类的名字来调用。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章