Answer to Question #258549 in Java | JSP | JSF for liza

Question #258549

When a subclass inherits from a superclass, it also inherits its methods; however, it can  


also override the superclass methods (as well as declare and implement new ones). Consider  the following Sports class: 


class Sports{ 

 String getName(){ 

 return "Generic Sports"; 

 } 

 void getNumberOfTeamMembers(){ 

 System.out.println( "Each team has n players in " + getName() ); 

 } 

Next, we create a Soccer class that inherits from the Sports class. We can override the  getName method and return a different, subclass-specific string: 


class Soccer extends Sports{ 

 @Override 

 String getName(){ 

 return "Soccer Class"; 

 } 

Note: When overriding a method, you should precede it with the @Override annotation. The  parameter(s) and return type of an overridden method must be exactly the same as those of  the method inherited from the supertype. 




1
Expert's answer
2021-10-29T12:16:57-0400


SOLUTION FOR THE ABOVE QUESTION


In this problem we will modify the getNumberOfTeamMembers() function to take a value n of int type as a parameter representing the number of team members of a given team.

Inside the main method, We will instantiate an object of the soccer class and prompt the user for to enter the number of team members and display then display the number of players in each team of the given sports name given by the overridden getName() function of the soccer class


SAMPLE PROGRAM OUTPUT




SOLUTION CODE FOR THE QUESTION


//In this problem we will modify the getNumberOfTeamMembers() function to take a value n of int type as
//a parameter representing the number of team members of a given team.
//Inside the main method,We will instantiate an object of the soccer class and prompt the user for to enter
//the number of team members and display then display the number of players in each team of the given
//sports name given by the overriden getName() function of the soccer class
package com.company;

import java.util.Scanner;

class Sports{

    String getName()
    {
        return "Generic Sports";
    }

    void getNumberOfTeamMembers(int n){

        System.out.println( "\nEach team has "+n +" players in " + getName() );

    }

}
class Soccer extends Sports{

    @Override

    String getName(){

        return "Soccer Class";
    }

}

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Soccer my_Soccer_object = new Soccer();
        System.out.print("\nEnter the number of members in each team: ");
        int number_of_members = sc.nextInt();
        my_Soccer_object.getNumberOfTeamMembers(number_of_members);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS