簡體   English   中英

構造函數中的 this.setMethod(parameter) 和 setMethod(parameter) 有什么區別? [爪哇]

[英]What is the difference between this.setMethod(parameter) and setMethod(parameter) in a constructor? [Java]

最近幾天我一直在嘗試學習類和對象,我意識到在構造函數中使用“this.set”和“set”沒有明顯的區別。 澄清

public Movie(String title,String director, String rating) {
        setTitle(title); 
        setDirector(director);
        setRating(rating);

public Movie(String title,String director, String rating) {
        this.setTitle(title); 
        this.setDirector(director);
        this.setRating(rating);

跑步時沒有區別。

有什么區別,如果有的話,哪個是更好的做法?

我原以為會出現某種錯誤,但它的工作原理完全一樣。 此外,我的導師使用“這個”。 在他的示例中將 setter 放入構造函數中。

謝謝。

在您的示例中調用 setter 方法時無需使用this (這樣做不是標准做法)。 但是,如果要在構造函數中設置與變量同名的字段,則需要使用this 例如:

public class Movie {
    private final String title;

    public Movie(String title) {
        this.title = title;
    }
}

如果您不指定this.title ,它會認為您正在嘗試將title變量分配給自己。

當您的 class 擴展了另一個 class 時,還需要關鍵字this來區分方法的不同實現(例如,您可以調用this.method()super.method() 。)

使用this.*您正在調用位於“this”實例的方法。 當從實現相同方法的 class 繼承時,您還有機會調用 super.setTitle()。

或者舉個例子:

class Foo
{
    public int baz()
    {
        return -1;
    }
}

class Bar extends Foo
{
    private Bar()
    {
        super.baz(); // returns -1
        this.baz(); // returns 1
    }

    public int baz()
    {
        return 1;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM