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.

コンストラクタについて

0
Posted at

卒業した生徒さんが作ったアプリのソースコードを拝見する機会があったので読み込んでいました。
 
授業ではインスタンスに引数を入れ別クラスのコンストラクタで値を初期化するという方法を学んだところでHさんは、

①個別クラスのコンストラクタ内で値を設定
②基本クラスのコンストラクタ内でインスタンスを作成&初期化

するというものだったのでこんな書き方も出来るのかと勉強させて頂きました。

以下はソースコードの一部です。

// クラス定義
public class Hoge {
    // 変数の定義
    private string name;
    private int num;
    // コンストラクタの定義
    // 通常であればここで変数の初期化を行う
    public test() {
        A a = new A(); B b = new B();
    }
}
// クラス定義
public class A {
    public Value() {
        twitter = "hage";
        num = 1;
    }
}
// Bクラス定義
public class B {
    public Value() {
        twitter = "hige";
        num = 2;
    }
}

私が考えていたクラス定義、インスタンス化、コンストラクタ

// クラスの定義
public class Hoge {
	// 変数の定義
	private string name;
	private int num;
	// コンストラクタ定義
	public Hoge(string name, int num) {
		// 変数nameと変数numを与えられた値で初期化
		this.name = name;
		this.num = num;
		// private name 変数へのアクセサ
		public name() {
			set {
				this.name = value;
			}
			get {
				return this.name;
			}
		}
		// private num 変数へのアクセサ
		public Num() {
			set {
				this.num = value;
			}
			get {
				return this.num;
			}
		}
	}
	public Main() {
		// インスタンス化と同時に個別の引数を格納する
		A a = new A("hage", 1);
		B b = new B("hige", 2);
	}
}

全くのド素人の意見ですが、人が書いたコードはより勉強になるなと実感しました

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?