Java Method Overriding by Super Keyword – Coder In Me

Problem :

When a method in a subclass overrides a method in superclass, it is still possible to call the overridden method using super keyword. It is a problem of Java Method Overriding by 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.

Views –

  • The super keyword in java is a reference variable that is used to refer parent class objects.
  • Super Keyword can be used to refer immediate parent class instance variable. super can be used to invoke immediate parent class method. super() can be used to invoke immediate parent class constructor.

The use of Java Method Overriding by Super Keyword

  • It is used inside a sub-class method definition to call a method defined in the super class. Private methods of the super-class cannot be called. Only public and protected methods can be called by the super keyword.
  • It is also used by class constructors to invoke constructors of its parentclass.

SYNTAX –

super.<method-name>([zero or more arguments]);

Given a partially  code for This –

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());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());











//// here write the modify code...










 System.out.println("My ancestor is a cycle who is "+ temp );
 }
 
}
class Solution{
 public static void main(String []args){
 MotorCycle M=new MotorCycle();
 }
}

MODIFY code for Java Method Overriding by Super Keyword HackerRank Problem –

String temp=super.define_me();

 

For more HackerRank problem solution click here

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

Leave a reply:

Your email address will not be published.