0
0

More than 3 years have passed since last update.

this()について

Posted at

this()の意味が分からなかったので書き残しておきます。

使用例

プログラムを実行した時間を求めるコードです。

qiita.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
    System.out.println(new Date());        

実行すると

qiita.java

Fri Feb 28 14:22:03 UTC 2020     

new Date()で何が起こっているか確認すると

Date.class

public class Date
    implements java.io.Serializable, Cloneable, Comparable<Date>
{
    private static final BaseCalendar gcal =
                                CalendarSystem.getGregorianCalendar();
    private static BaseCalendar jcal;

    private transient long fastTime;

    private transient BaseCalendar.Date cdate;

    private static final long serialVersionUID = 7523967970034938905L;

    public Date() {
        this(System.currentTimeMillis());
    }

    public Date(long date) {
        fastTime = date;
    }
}   

出ました。this()。
System.currentTimeMillis()はOSの時間を返してくれるメソッドのようです。
this()で呼ばれるのはこの下にあるコンストラクタのこいつ。

Date.class

    public Date(long date) {
        fastTime = date;
    }  

オーバロードされていることがわかります。このコンストラクタは、フィールドに時間を入れているだけです。
つまり、this()は同じ引数をもつコンストラクタを呼び出すという意味でした。

this()のまとめ

・this()はコンストラクタを呼び出すときに使われる。
・どのコンストラクタを呼ぶか引数で判断する。
・デフォルト値を設定したい場合に利用できる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0