Javaプログラミング初心者のためのページ -21ページ目

キーワード:super:問題1

何が表示されるか?

A. A1が表示される
B. A2が表示される
C. A1もA2も表示される
D. 何も表示されない

======ソースコード
class A {
    A() {
        System.out.println("A1");
    }
    A(int x) {
        System.out.println("A2");
    }
}

class B extends A {
    B() {
    }
}

class M {
    public static void main(String[] args) {
        B b = new B();
    }
}

======
正解: A.

オブジェクトの参照(その1)

オブジェクトはスーパークラスの型でも代入可能です。クラス継承の最上位のクラスはjava.lang.Objectクラスなので、Object型の変数にはどのようなオブジェクトでも代入可能です。


=======クイズ
class A {}
class B extends A {}

のとき、以下のコードはどの様な結果になるか。
・ 実行時エラー
・ コンパイルエラー
・ 正常実行

A a1 = new A();
A a2 = new B();
B b1 = new A();
B b2 = new B();
Object o1 = new A();
Object o2 = new B();

------- 正解
A a1 = new A();    → 正常実行
A a2 = new B();    → 正常実行
B b1 = new A();    → コンパイルエラー
B b2 = new B();    → 正常実行
Object o1 = new A(); → 正常実行
Object o2 = new B(); → 正常実行

Stringの比較

通常、Stringオブジェクトの「文字列が等しいか?」を比較するにはequalsメソッドを使用します。

Stringオブジェクトの==による比較は、「参照先が全く同じオブジェクトか?」を比較します。
したがって、String x = new String("xxx");として作成したStringオブジェクトが複数あった場合、別の参照先になるため==の比較結果はfalseになります。
ただし、String x = "xxx";として作成すると、コンパイル段階で参照先も同じオブジェクトとして作成するため==の比較結果はtrueになります。


class String001A{
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "hello";
        System.out.println(str1 == str2);
        System.out.println(str1.equals(str2));
    }
}
--------実行結果
true
true

/*******************************************************/
class String001B{
    public static void main(String[] args) {
        String str1 = new String("hello");
        String str2 = new String("hello");
        System.out.println(str1 == str2);
        System.out.println(str1.equals(str2));
    }
}
--------実行結果
false
true

/*******************************************************/
class String001C{
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = new String("hello");
        System.out.println(str1 == str2);
        System.out.println(str1 == str2);
    }
}
--------実行結果
false
true