當一個對象建立後,Java虛擬機器(JVM)就會給這個對象分配一個引用自身的指標,這個指標的名字就是this。並且this只和特定的對象關聯,而不和類關聯,同一個類的不同對象有不同的this。用法:
(1)this(參數):調用本類中另一種形式的建構函式
class Point { private int x,y; public Point(int x,int y) { this.x=x; //this它代表當前對象名 this.y=y; } public Point() { this(0,0); } }
(2)如果函數的形參與類中的成員變數同名,這時需用this來指明成員變數名,該功能在(1)中也體現
class Point { private int x,y; public Point(int x,int y) { this.x=x; //this它代表當前對象名 this.y=y; } }
(3)如果函數的局部變數與成員變數相同時,成員變數會被隱藏。此時如果要用到成員變數的話,就需this。
class Point { private int x = 3; public Point() { int x; x = 5; system.out.println(x); //輸出5 system.out.println(this.x); //輸出3 } }
====================================================================================================================
super的各種用法
(1)使用特殊變數super提供對父類的訪問,可以使用super訪問父類被子類隱藏的變數或覆蓋的方法
class Animal { int height,weight; void Animal() { System.out.println("Animal construct!");} void eat() { System.out.println("Animal eat!"); } void sleep() { System.out.println("Animal sleep!"); } void breathe() { System.out.println("Animal breathe!"); } } class Fish extends Animal { Fish(){ System.out.println("Fish construct"); } void breathe(){ //override method breathe() super.breathe();//在子類中用super訪問被覆蓋的父類函數 System.out.println("Fish bubble"); } } public class TestNew {public static void main(String[] args) {// TODO Auto-generated method stubFish fn=new Fish(); fn.breathe();}}
編譯運行結果:
Fish construct
Animal breathe!
Fish bubble