LoginSignup
0
0

Java silver向け 例題 継承 ポリモーフィズム

Last updated at Posted at 2024-04-07

次のコードの実行結果を答えてください。

class Human {
	String name = "ADAMU";
 
	void jump() {
		System.out.println("Jump");
	}
 
	void selfIntroduction() {
		System.out.println("My name is " + name);
	}

     static void sample() {
		System.out.println("sample Human");
	}
}

class OldMan extends Human {
	String name = "KEBBY";
	
    @Override
	void jump() {
		System.out.println("Step");
	}
 
	@Override
	void selfIntroduction() {
		System.out.println("My name is " + name);
	}

     static void sample() {
		System.out.println("sample OldMan");
	}
 
	void attack() {
		System.out.println("Attack!");
	}
} 

public class ExampleFour {
	public static void main(String[] args) {
		
		Human human01 = new OldMan();
		
		System.out.println(human01.name);
		human01.jump();					
		human01.selfIntroduction();	
        human01.sample();
	}
}

正解













ADAMU
Step
My name is KEBBY
sample Human


スーパークラスの型(Human型)で宣言した変数 human01 にサブクラス(new OldMan())のインスタンスは代入できます。 サブクラスのオブジェクトをスーパークラスの型の変数に代入した場合、 インスタンスメソッド"以外"はスーパークラスのメンバが呼び出されます。
System.out.println(human01.name);	//スーパークラスのメンバが優先的に呼び出されている
human01.jump();						//サブクラスのメソッドから優先的に呼び出される
human01.selfIntroduction();			//サブクラスのメソッド経由でサブクラスのメンバが呼び出されている
human01.sample();					//staticメソッドのためスーパークラスから呼び出される。
//human01.attack();                   Human型にattackメソッドがないためコンパイルエラー

サブクラス型の変数にスーパークラスのオブジェクトを代入するとコンパイルエラー。 キャストするとコンパイルは通りますが実行時エラーが発生します。
//コンパイルエラー
OldMan human02 = new Human();

//実行時ClassCastException
OldMan human02 = (OldMan) new Human();
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