舉例講解Java編程中this關鍵字與super關鍵字的用法
this
總要有個事物來代表類的當前對象,就像C++中的this指針一樣,Java中的this關鍵字就是代表當前對象的引用。
它有三個主要的作用:
1、在構造方法中調(diào)用其他構造方法。
比如有一個Student類,有三個構造函數(shù),某一個構造函數(shù)中調(diào)用另外構造函數(shù),就要用到this(),而直接使用Student()是不可以的。
2、返回當前對象的引用。
3、區(qū)分成員變量名和參數(shù)名。
看下面的例子:
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)調(diào)用其他構造函數(shù) 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這個關鍵字?
第一、看父類的構造
子類構造時要先調(diào)用父類的默認構造函數(shù)的,這與C++的構造屬性一致。當父類有多個構造函數(shù)時,你需要指定調(diào)用哪個。這是就需要使用super(arg1,arg2...)。
需要注意的是,在子類的構造函數(shù)中調(diào)用基類的構造函數(shù)時,必須要把super寫作最前面,否則報錯。
第二,在子類覆蓋父類的一些方法中再調(diào)用父類的此方法。大家都知道,在子類中覆蓋父類的一些方法是面向?qū)ο笾卸鄳B(tài)的一種方式,而因為其他種種原因,需要在此方法中調(diào)用父類的此方法,用以區(qū)分,此時需要使用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++直接用基類的名字來調(diào)用。
相關文章
Springboot+AOP實現(xiàn)時間參數(shù)格式轉(zhuǎn)換
前端傳過來的時間參數(shù),后端可以自定義時間格式轉(zhuǎn)化使用,這樣想轉(zhuǎn)成什么就轉(zhuǎn)成什么。本文將利用自定義注解AOP實現(xiàn)時間參數(shù)格式轉(zhuǎn)換,感興趣的可以了解一下2022-04-04使用IDEA搭建SSM框架的詳細教程(spring + springMVC +MyBatis)
這篇文章主要介紹了使用IDEA搭建SSM框架的詳細教程 spring + springMVC +MyBatis,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05