題目描述

一個在子類別的方法覆寫了父類別的方法,這個子類別仍然可以使用「super」這個關鍵字去呼叫到父類別被覆寫的方法。如果您寫了「super.func()」去呼叫「 func()」這個方法,會呼叫到父類別的「func()」方法。



您需要讓您的程式能輸出以下文字:

Hello I am a motorcycle, I am a cycle with an engine.
My ancestor is a cycle who is a vehicle with pedals.

原題網址

https://www.hackerrank.com/challenges/java-method-overriding-2-super-keyword

解題概念

使用super關鍵字可以在子類別呼叫被子類別覆寫的父類別方法。

參考答案

import java.util.*;
import java.io.*;


class BiCycle
{
   String define_me()
   {
      return "a vehicle with pedals.";
   }
}

class MotorCycle extends BiCycle
{
   String define_me()
   {
      return "a cycle with an engine.";
   }
   
   MotorCycle()
   {
      
      
      System.out.println("Hello I am a motorcycle, I am "+ define_me());
      String temp=super.define_me();
      System.out.println("My ancestor is a cycle who is "+ temp );
   }
   
}
class Solution{
   public static void main(String []argh)
   {
      MotorCycle M=new MotorCycle();
   }
}