0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Javaを基本からまとめてみた【this / コンストラクタの呼び出し】

Last updated at Posted at 2023-03-09

this / コンストラクタの呼び出し

  • 『this』は『このインスタンス』と言う意味を表す。
this() : コンストラクタ
this.変数名 : フィールド変数 
  • コンストラクタからコンストラクタを呼ぶ際は、呼び出し元のコンストラクタの先頭で呼ばなければならない。

  • メソッド内のローカル変数とフィールドヘンスが同じ名称の場合、ローカル変数が優遇される

Sample2.java


class Sample2_drive {
 public static void main(String[] args)

 System.out.println("車を場に搭乗させる")
 car chocoCar = new Sample2_car();

//コンスタントラクタは一番深いものから動く

 car mocoCar = new Sample2_car("クーペ","red",80);

//コンストラクタ①(引数無し)
Sample2_car(){
 System.out.println("コンストラクタ① (引数無)");
 carModel = "未登録"; //車種
 color = "未登録"; //色
 speed = 0; //現在の速度
 System.out.println("○ ○");
}

//コンストラクタ②(引数有り)
Sample2_car(String cm, String cl, int sp){
 this() //コンストラクタ①(引数無し)の起動
 System.out.println("コンストラクタ② (引数有)");
 carModel = cm; //車種
 color = cl; //色
 speed = 0; //現在の速度
 System.out.println("○ ○");

参考サイト

【Java-オブジェクト指向】Javaプログラミングの「オブジェクト指向」が絶対理解できる講座【プロ講師が丁寧解説】

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?