Java Method Overriding 2 (Super Keyword)-HackerRank Solution

0

When a method in a subclass overrides a method in superclass, it is still possible to call the overridden method using super keyword. If you write super.func() to call the function func(), it will call the method that was defined in the superclass.

 



You are given a partially completed code in the editor. Modify the code so that the code prints the following text:

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

 

Solution


  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(); //Fix this line
  System.out.println("My ancestor is a cycle who is "+ temp );
    }
  }

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


 
Result


Explanation
 
What is super keyword:The super keyword in Java is used in subclasses to access superclass members

Use of super  keyword

  • To call methods of the superclass that is overridden in the subclass.
  • To access attributes (fields) of the superclass if both superclass and subclass have attributes with the same name.
  • To explicitly call superclass no-arg (default) or parameterized constructor from the subclass constructor.
Method Overriding: If subclass (child class) has the same method as declared in the parent class, it is known as method overriding.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !