簡體   English   中英

請幫我理解java結構

[英]Please help me to understand java structure

public class MyDate {
    private int day = 1;
    private int month = 1;
    private int year = 2000;

    public MyDate(int day, int month, int year) 
    {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    public MyDate(MyDate date) 
    {
        this.day = date.day;
        this.month = date.month;
        this.year = date.year;
    }

    /*
        here why do we need to use Class name before the method name?
    */
    public MyDate addDays(int moreDays) 
    {
        // "this" is referring to which object and why?
        MyDate newDate = new MyDate(this);
        newDate.day = newDate.day + moreDays;

        // Not Yet Implemented: wrap around code...
        return newDate;
    }

    public String toString()
    {
        return "" + day + "-" + month + "-" + year;
    }
}

this將引用您將創建的當前對象實例。 在任何java方法中, this總是保存對其對象實例的引用。

一個例子 -

MyDate myDate = new MyDate(10, 10, 2012);
myDate.addDays(10);

您想知道的newDate行將指向此處創建的newDate對象。 線 -

MyDate newDate = new MyDate(this);

將使用此構造函數 -

public MyDate(MyDate date) {
    this.day = date.day;
    this.month = date.month;
    this.year = date.year;
}

創建並返回一個新對象,向其傳遞對當前對象實例的引用,以便它可以復制其日,月和年值。

答案為1.在方法名稱之前使用類名稱意味着您將返回MyDate類型的引用變量。它只是一個返回類型。

答案為2.這是指當前對象是您的MyDate類對象。 為了使用'new'關鍵字創建一個新對象,您可以使用'this'作為快捷方式。但是,您應該在您嘗試引用對象的類中找到'this'。

here why do we need to use Class name before the method name.

因為這是一個返回MyDate類型引用的方法

"this" is referring to which object and why?

是指當前的對象

這里為什么我們需要在方法名稱之前使用類名。

您正在返回一個MyDate對象,該類名是該函數的返回類型。

“這個”指的是哪個對象,為什么?

this總是指調用方法的當前對象。 它看起來是將當前的MyDate對象復制到一個新對象並返回它。

暫無
暫無

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

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