user1766598
user1766598

Reputation:

Assistance with building a sports game with multiple classes

*UPDATED CODE*I have to write a class encapsulating a sports game, which inherits from Game. Where the game has the following additional attributes: whether the game is a team or individual game, and whether the game can end in a tie.

I am not familiar with inheritance and am wondering if you guys could help get me on the right path. I have been reading about inheritance all day and just don't understand it. My question is: how to I build build this project to incorporate inheritance, what can/should be inherited and how do you do it? Thanks

I think I may have figured a bit out, but can some one help with the toString method and how to code the canTie?

public class Game 
{
public static void main(String[] args) 
{
    Question39 gm1 = new Question39();
    System.out.println("Game type: "+ gm1.getGameType() + "\n"
                       + "Can it tie: " + gm1.getCanTie());
}

public Game()
{

}  
}

Second Class

public class SportsGame extends Game 
{
public SportsGame()
{
    super();
}

public String toString()
{
    String output ="hey"; 
    return output;
}

 //Accessors (Getters)
public String getGameType() 
{
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter number of players");
    int players = scan.nextInt();

    if (players > 2)
    {
        return "Team";
    }    
    else 
    {
        if (players ==2)
        {
            return "Individual";
        }

        else
        {
            return "N/A";
        }
    }

}

public String getCanTie()
{
    String canTie = "yes";
    String cantTie = "no";

    if (1==1) 
            {
                return canTie;
            }
    else 
            {
                return cantTie;
            }
}
}

Upvotes: 0

Views: 663

Answers (1)

wchargin
wchargin

Reputation: 16047

Because your SportsGame "is-a" Game, it should, as you say, inherit from Game.

The syntax for that is:

public class SportsGame extends Game {
    // ....
}

Your classes should probably be like this:

// In Game.java:
public abstract class Game {
    public abstract boolean isTeamGame();
    public abstract boolean canEndInTie();
}

 

// In SportsGame.java:
public class SportsGame extends Game {
    // You'll need to implement the methods from Game here.
    // For example:

    @Override
    public boolean isTeamGame() {
        return true;
    }

    @Override
    public boolean canEndInTie() {
        return true;
    }
}

Alternatively, you could initialize those values to a variable in a constructor, and then return them from those methods.

Upvotes: 1

Related Questions