1. 程式人生 > 實用技巧 >super和this的三種用法

super和this的三種用法

super用來訪問父類內容

1:在子類的成員方法中,訪問父類的成員變數

public class Fu {
    protected int num = 10;
}
public class Zi extends Fu{
    protected int num=20;
    public void moth(){
        System.out.println("這是子類的成員方法");
        System.out.println("這是父類的成員變數:"+super.num);
    }
public class Demo2 {
    public static
void main(String[] args) { Zi zi=new Zi(); zi.moth(); } }

執行結果:


2:在子類的成員方法中,訪問父類的成員方法

public class Fu {
    public void moth() {
        System.out.println("這是父類的成員方法");
    }
} 
public class Zi extends Fu{
    public void moth(){
        System.out.println("這是子類的成員方法");
        
super.moth(); } }
public class Demo2 {
    public static void main(String[] args) {
        Zi zi=new Zi();
        zi.moth();
    }
}

執行結果:


3:在子類的構造方法中,訪問父類的構造方法

public class Fu {
    public Fu() {
        System.out.println("這是父類的構造方法");
    }
}
public class Zi extends Fu{
    public Zi() {
        
super(); System.out.println("這是子類的構造方法"); } }
public class Demo2 {
    public static void main(String[] args) {
        Zi zi=new Zi();
    }
}

執行結果:


this的三種用法。

this用來訪問本類內容

1:在本類的成員方法中,訪問本類的成員變數

public class Test2 {
    int num=10;
    public void moth(){
        int num=20;
        System.out.println("這是本類的成員方法");
        System.out.println(this.num);
    }
public class Demo2 {
    public static void main(String[] args) {
        Test2  test2=new Test2();
        test2.moth();
    }
}

執行結果:


2:在本類的成員方法中,訪問本類的另一個成員方法

public class Test2 {
    int num=10;
    public void moth(){
        System.out.println("這是本類的成員方法1");
        this.moth2();
    }
    public void moth2(){
        System.out.println("這是本類的成員方法2");
    }
}
public class Demo2 {
    public static void main(String[] args) {
        Test2  test2=new Test2();
        test2.moth();
    }
}

執行結果:


3:在本類的構造方法中,訪問本類的另一個構造方法

public class Test2 {
    int num;

    public Test2() {
        System.out.println("這是無參構造");
    }

    public Test2(int num) {
        this();
        this.num = num;
        System.out.println(this.num);
    }
}
public class Demo2 {
    public static void main(String[] args) {
        Test2  test2=new Test2(20);
    }
}

執行結果:


在各自的第三中用法中,都必須是構造方法語句的第一句,也只能有唯一一句,不能同時使用。