In this HackerRank Java Method overriding problem in the java programming language, you need to complete the code in your editor by writing an overridden getNumberOfTeamMembers method that prints the same statement as the superclass' getNumberOfTeamMembers method, except that it replaces n with 11 (the number of players on a soccer team).


HackerRank Java Method Overriding problem solution


HackerRank Java Method Overriding problem solution.

import java.util.*;
class Sports{

   String get_name()
   {
      return "Generic Sports";
   }
   void get_number_of_team_members()
   {
      System.out.println("Each team has n players in "+get_name());
   }
}

class Soccer extends Sports
{
   String get_name()
   {
      return "Soccer Class";
   }
   //Complete the code
    void get_number_of_team_members(){
        System.out.println("Each team has 11 players in Soccer Class");
    }
}
public class Main
{
   
   public static void main(String []args)
   {
      Sports C1=new Sports();
      Soccer C2=new Soccer();
      System.out.println(C1.get_name());
      C1.get_number_of_team_members();
      System.out.println(C2.get_name());
      C2.get_number_of_team_members();
   }
}


Second solution in java8 programming.

import java.util.*;
class Sports{

    String getName(){
        return "Generic Sports";
    }
  
    void getNumberOfTeamMembers(){
        System.out.println( "Each team has n players in " + getName() );
    }
}

class Soccer extends Sports{
    @Override
    String getName(){
        return "Soccer Class";
    }

    // Write your overridden getNumberOfTeamMembers method here
    @Override
void getNumberOfTeamMembers() {
    System.out.println("Each team has 11 players in " + getName());
}

}

public class Solution{
  
    public static void main(String []args){
        Sports c1 = new Sports();
        Soccer c2 = new Soccer();
        System.out.println(c1.getName());
        c1.getNumberOfTeamMembers();
        System.out.println(c2.getName());
        c2.getNumberOfTeamMembers();
  }
}