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 5 years have passed since last update.

JAVA コンストラクタの呼び出し処理

Last updated at Posted at 2019-02-18

どうもおしょうです。
以下、自分のメモ用で記事を書きます。

まずはメイン処理のMain.javaを作成

Main.java
class Main {
    public static void main(String[] args) {
        // インスタンスの生成と変数への代入
        Sample sample = new Sample();

        System.out.println("【サンプル】");
        System.out.println("名前:" + sample.name);
    }
}

次にコンストラクタを呼び出すSample.javaを作成

Sample.java
class Sample {
    // 定数の定義
    public String name;

    // コンストラクタの定義
    Sample() {
        this.name = "おしょう";
    }
}

Main.javaの4行目にある

Sample sample = new Sample();

でSample.javaのコンストラクタ(Sample.javaの6~8行目)を実行します。

その後、Main.javaの6行目にある

System.out.println("名前:" + sample.name);

この処理で、Sample.javaのコンストラクタによってセットされた

name(中身に"おしょう"がセットされている)を処理結果のコンソールに出力します。

2つのjavaファイルをコンパイルして実行した結果は...

【サンプル】
名前:おしょう

となります。

Sample.javaの定数をprivateにして呼び出せたような気がするが...
何かより良い書き方があればご指摘お願いします。

以上、失礼します。

0
0
1

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?