Skip to content

Instantly share code, notes, and snippets.

@Nkzn
Last active May 20, 2017 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nkzn/1e8f97c1f493484880cd564dacfa3c7a to your computer and use it in GitHub Desktop.
Save Nkzn/1e8f97c1f493484880cd564dacfa3c7a to your computer and use it in GitHub Desktop.
Javaでフィールドに代入して初期化するのとコンストラクタの中で初期化するのって微妙に違うことを表したかったんだけど、さほど納得感が出なかった・・・
public class Main {
public static void main(String... args) {
SuperHoge superHoge_1 = new SuperHoge();
System.out.println(superHoge_1.sum()); // => 2 (a:1, b:1)
SuperHoge superHoge_2 = new SuperHoge(2);
System.out.println(superHoge_2.sum()); // => 3 (a:1, b:2)
SubHoge1 subHoge1_1 = new SubHoge1();
System.out.println(subHoge1_1.sum()); // => 2 (a:1, b:1)
SubHoge1 subHoge1_2 = new SubHoge1(2);
System.out.println(subHoge1_2.sum()); // => 4 (a:1, b:3)
SubHoge2 subHoge2_1 = new SubHoge2();
System.out.println(subHoge2_1.sum()); // => 1 (a:0, b:1)
SubHoge2 subHoge2_2 = new SubHoge2(2);
System.out.println(subHoge2_2.sum()); // => 7 (a:0, b:7)
}
}
public class SubHoge1 extends SuperHoge {
protected int a = 0; // これは使われない
public SubHoge1() {
super();
}
public SubHoge1(int value) {
this();
this.b += value;
}
}
public class SubHoge2 extends SuperHoge {
{
this.a = 0; // これはaを上書きできる
}
public SubHoge2() {
super();
}
public SubHoge2(int value) {
super(3 + value); // こういうのはコンストラクタならではかなと
this.b += value;
}
}
public class SuperHoge {
protected int a = 1;
int b;
protected SuperHoge() {
this.b = 1;
}
protected SuperHoge(int value) {
this.b = value;
}
public int sum() {
return a + b;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment