Skip to content

Instantly share code, notes, and snippets.

@MasatoshiTada
Created December 8, 2021 06:44
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 MasatoshiTada/07bd902ddf91cf4b1407c3c3e399f6fa to your computer and use it in GitHub Desktop.
Save MasatoshiTada/07bd902ddf91cf4b1407c3c3e399f6fa to your computer and use it in GitHub Desktop.
Javaの継承・インタフェース・ポリモーフィズムの理解度チェック。理由まで説明できれば100点!解答はコメント参照。
class Parent { /*メソッド等は省略*/ }
class Child extends Parent { /*メソッド等は省略*/ }
コンパイルが通る(=エラーにならない)のは?
(1) Parent p = new Parent();
(2) Parent p = new Child();
(3) Parent p = null;
(4) Child c = new Parent();
(5) Child c = new Child();
(6) Child c = null;
abstract class Parent { /*メソッド等は省略*/ }
class Child extends Parent { /*メソッド等は省略*/ }
コンパイルが通る(=エラーにならない)のは?
(1) Parent p = new Parent();
(2) Parent p = new Child();
(3) Parent p = null;
(4) Child c = new Parent();
(5) Child c = new Child();
(6) Child c = null;
interface Parent { /*メソッド等は省略*/ }
class Child implements Parent { /*メソッド等は省略*/ }
コンパイルが通る(=エラーにならない)のは?
(1) Parent p = new Parent();
(2) Parent p = new Child();
(3) Parent p = null;
(4) Child c = new Parent();
(5) Child c = new Child();
(6) Child c = null;
class Parent {
void method1() {
System.out.println("1A");
}
}
class Child extends Parent {
@Override
void method1() {
System.out.println("1B");
}
void method2() {
System.out.println("2B");
}
}
コンパイルが通る(=エラーにならない)のは?
コンパイルが通る場合、実行すると何が表示される?
(1)
Parent p = new Parent();
p.method1();
(2)
Child c = new Child();
c.method1();
(3)
Parent p = new Child();
p.method1();
(4)
Child c = new Child();
c.method2();
(5)
Parent p = new Child();
p.method2();
@MasatoshiTada
Copy link
Author

Q1の解答

⭕(1) Parent p = new Parent();
⭕(2) Parent p = new Child();
⭕(3) Parent p = null;
❌(4) Child c = new Parent();
⭕(5) Child c = new Child();
⭕(6) Child c = null;

@MasatoshiTada
Copy link
Author

Q2の解答

❌(1) Parent p = new Parent();
⭕(2) Parent p = new Child();
⭕(3) Parent p = null;
❌(4) Child c = new Parent();
⭕(5) Child c = new Child();
⭕(6) Child c = null;

@MasatoshiTada
Copy link
Author

MasatoshiTada commented Dec 8, 2021

Q3の解答

❌(1) Parent p = new Parent();
⭕(2) Parent p = new Child();
⭕(3) Parent p = null;
❌(4) Child c = new Parent();
⭕(5) Child c = new Child();
⭕(6) Child c = null;

@MasatoshiTada
Copy link
Author

Q4の解答

(1)
Parent p = new Parent();
p.method1(); // "1A"と表示

(2)
Child c = new Child();
c.method1(); // "1B"と表示

(3)
Parent p = new Child();
p.method1(); // "1B"と表示

(4)
Child c = new Child();
c.method2(); // "2B"と表示

(5)
Parent p = new Child();
p.method2(); // コンパイルエラー

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment