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 this project to incorporate inheritance, what can/should be inherited and how do you do it? Thanks

First class

public class Chap10Quest39 
{
public static void main(String[] args) 
{
    Game tennis = new Chap10Quest39().new Game("individual","tie");     

    System.out.println(tennis + "\n");
    System.out.print(tennis.getGameType() + " " + tennis.getWin() + " " + "\n");
}
}

Second

public class Game 
{
//Instance Variables
private String gameType;
private String win;

public Game() 
{
    gameType = null;
    win = null;
}

//Constructor
public Game(String gameType, String win) 
{    
    this.gameType = gameType; 
    this.win = win;
}

//Accessors (Getters)
public String getGameType() 
{
return gameType;
}

public String getWin()
{
    return win;
}

//Mutators (Setters)
public void setGameType(String GameType)
{
    this.gameType = gameType;
}

public void setWin(String win)
{
    this.win = win;
}

// toString Method
public String toString()
{
    return "Type: " + gameType + "; Win: " + win; 
}
}    

The idea of inheritance is simple but powerful: When you want to create a new class and there is already a class that includes some of the code that you want, you can derive your new class from the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write (and debug!) them yourself.
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

import com.daniweb.GameClass;;
public class Chap10Quest39 extends GameClass {//to inherit parent property just extend the parent class to child class
    public Chap10Quest39(String string, String string2){//
    super(string,string2);}//call super class constructor with two String parameters
    public static void main(String[] args) 
    {

        GameClass tennis = new Chap10Quest39("name","hgh");     //shows the use of an object of one type in place of another type, among the objects permitted by inheritance and implementations.then tennis is both an GameClass and a Chap10Quest39 type. 

        System.out.println(tennis + "\n");
        System.out.print(tennis.getGameType() + " " + tennis.getWin() + " " + "\n");
    }
    }

The point of extending a class is not to reuse the code in that class. If that is all you want then you should just create an instance of that class.

The real benefit of extending a class A is when there exists code like a method doSomething(A a) and you want to be able to call that method using your class B as its argument. Since doSomething requires an A, what you want to do is make B a kind of A, so not only doSomething, but all other code made to work with As can also work with Bs.

When every B is an A, then you have inheritance because class B must inherit every field and method of class A, unless B defines its own version of some of those methods. There is simply no option for B to not have something that A has, because that would mean that you could have a B which is not an A.

So in this example, a sports game is a game, so it makes sense for a sports game class to extend the Game class. Since it is absurd to imagine a sports game that is not a game, all of the fields and methods of Game must make sense for the sports game class.

The most important thing is to remember that you should not use inheritance just as a way to reuse the methods of a class. No matter how many methods and fields from Game you need for your Stadium class, a stadium is not a game, and so Stadium should not extend Game.

You should also avoid calling your classes things like GameClass. That may sound like a good name for a class, but that would mean that every instance of GameClass is a game class, when what you probably want is for every instance to be a game; the name of your class is a name that gets applied to every individual instance, not to the collection of all instances. For the same reason you normally want to avoid plural class names.

commented: ehm ... whut? for remarks: read my reply. -3
commented: the above quote is taken from oracle site -1
commented: The thought behind this post is correct and known as good practice: "Use inheritance to model IS A relationships" and not just for the sake of reusing code. +13

bguild:

The point of extending a class is not to reuse the code in that class.

this makes no sense. the actual point of inheritance is that you can re-use the code without re-writing it .

The real benefit of extending a class A is when there exists code like a method doSomething(A a) and you want to be able to call that method using your class B as its argument.

ever heard of (marker) interfaces? inheritance sure isn't the only way to achieve polymorphism. besides, if that's what you wanted, you could always make sure your methods accept parameters of the type "Object".

When every B is an A, then you have inheritance because class B must inherit every field and method of class A,

not really. I assume you are aware of private members, and the fact that they're not inherited?

The most important thing is to remember that you should not use inheritance just as a way to reuse the methods of a class. No matter how many methods and fields from Game you need for your Stadium class, a stadium is not a game, and so Stadium should not extend Game.

actually, yes, that is one of the best reasons there are. if they have the same implementation, it's actually a very good thing to do. point is, if your "Stadium" and "Game" classes have the same methods, there's something awfully wrong with your analysis. you should delete your project and start over.

You should also avoid calling your classes things like GameClass. That may sound like a good name for a class, but that would mean that every instance of GameClass is a game class, when what you probably want is for every instance to be a game; the name of your class is a name that gets applied to every individual instance, not to the collection of all instances. For the same reason you normally want to avoid plural class names.

there is nothing wrong with names like GameClass: they tell the developer exactly what is covered in there and they follow the naming conventions. sure, Game is also well chosen, but not really better then GameClass.

the name of your class is a name that gets applied to every individual instance, not to the collection of all instances.

I really have ... no idea what you are trying to say there. the name of the class is applied to the instances? not really. the name of the class just states of which type the instances are. it's not as if it influences how the instance 'll behave or work. as long as the developer knows what the class is/does, there 's no problem at all.

Even Z (if well documented) can be a decent classname. I'm not saying I would use it, though.

and yet again. if you bother to downvote it, at least have the decency to say WHY.

if you bother to downvote it, at least have the decency to say WHY.

commented: It took you 4 hours to come up with what's been said in the previous post? Also next time please provide a link: "oracle site" is pretty vague. -3

OK guys, that's enough now. Please restrict yourselves to answering bobit's orignal post. Thanks.

@mvmalderen:

It took you 4 hours to come up with what's been said in the previous post?

first of all i don't sit 24 hours in this forum to reply and neither i downvote without giving reasons.
Secondly,i also want to know the reason for downvote,not only some persons can ask this question

Also next time please provide a link: "oracle site" is pretty vague.

As for this is concerned,if you are java professional you might know that there are only 1 oracle site for java docs. http://docs.oracle.com/javase/
As for reference is concerned http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

It's first time i have ever heard this type of qustions.

Ok, I have updated my code. Please let me know if this is better. Can anyone help with the toString and the canTie?

First Class

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 Question39 extends Game 
{
public Question39()
{
    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;
            }
}
}

Let's start from the beggining ...
The main points in your assignment are:

  1. "inherits from Game". From those, we have that the base class would be Game.
  2. "game is a team or individual game". Look closer at the wording. Game is Team Game. And game is Individual game. From which, we can assume, that there're our child classes. "Is" is describing one of the class-to-class relationships. You can easily read this as "Team Game is also a Game" and "Individual game is also a Game".
  3. "game can end in a tie". From this we have a characteristic, that have a Game class, which we extracted at the first. step.

I don't know, where you took the "toString()" thing and the others ... if there're some other details on your project, please post them. By now, let's tie to the conditions that we have:

From step one we have:

public class Game
{

}

From the second step, we're adding two child classes, which have an "is"-relationship with our base class:

public class TeamGame extends Game
{

}

public class IndividualGame extends Game
{

}

And at the 3rd step, we determine, that we have a common characteristic, that would reside at the "Game level".

public class Game
{
    boolean canTie;
}

That's pretty much all, that we know from your assignment, but I hope, you got the idea ;)

@Antenka here is the complete assignment: Write a class encapsulating a Sports Game, which inherits from Game. A sports game has the following additional attributes: whether the game is a team or individual game and whether the game can end in a tie. Code the constructor and the toString method of the new class. You also need to include a client class to test your code.

Ok, seems like I did the most work for you :) Try to complete my code, according to your assignment and show us what you come up with. Ask, if anything in my explanation isn't clear for you, or if there any troubles with completing the task.

@antenka I dont follow why I would need a Team class and an Individual class. What all would I need to have in the Game class? wouldnt I make it whether I decide if the game is a team or individual game within the Sports Game class, along with if it can end in a tie? What methods and varibles are needed in the Game class?

How do you determine if a game can tie?

From the wording of the assignment I think that Antenka is probably wrong about TeamGame and IndividualGame. It looks more likely that SportsGame is expected and that SportsGame should have two fields to represent whether it is individual and whether it can tie.

From the wording, I also expect that the Game class is given to you, but if you don't have a Game class already then you could just use an empty class like public class Game {}. Since your assignment says nothing about what Game needs to do, it may as well do nothing. It might be a good idea to ask for clarification about that from whoever gave you the assignment.

How do you determine if a game can tie?

You only need to determine that for sports games according to your instructions, so I suggest that you make it a parameter of the constructor for your sports game class.

I dont follow why I would need a Team class and an Individual class

Ok, let's start from the understanding OOP. The Game class is clearly specified in your assignment, so I'll pass it. What is a base class and what are the child ones? The base class is intended to describe the common entity. The common characteristics and behaviour of some group of the other, more-specific entities. By now, it sounds confusing, but let's see and example: suppose, we have to describe a few birds (let's take a sparrow and a penguin). We have some common characteristics for all the birds (like size and color) and some differences (some birds can't fly).

If we'd start to describe the birds in java, we'd create 2 classes:

class Sparrow{
    String color = "brown";
    String size = "small";

    public void fly(){
        //some code to make a sparrow flying
    }
}

class Penguin{
    String color = "black";
    String size = "medium";
}

All the classes contains described characteristics, but there's something wrong ... what if we have to describe a 20 birds ... should we copy-paste all that to all the classes? And here comes OOP (one of the many ways to apply it). We can extract the default characteristics into a base class Bird and just say something like: "The sparrow has all the Bird stuff, but with it's own detailes".
So, we move the common staff into a base Bird class:

class Bird
{
    public String color;
    public String size;

    public Bird(String color, String size){
        this.color = color;
        this.size = size;
    }
}

And, back to our wording ("The sparrow has all the Bird stuff, but with it's own detailes"), making some changes to our child classes:

class Sparrow extends Bird{
    public Sparrow(){
        super("brown", "small");
    }

    public void fly(){
        //some code to make a sparrow flying
    }
}

class Penguin extends Bird{
    public Penguin(){
        super("black", "meduim");
    }
}

So, what we have now: both classes has the common characteristics and at the same time, they look differently. To Test that, we can create the objects in the main prog and look, what we have inside the created objects:

Bird bird1 = new Sparrow();
Bird bird2 = new Penguin();

Same thing should be in your code. The Game class describes variety of games. In your situation, you have 2 of them: Team and Individual.

What all would I need to have in the Game class?

The Game class should contain all the common information, that will be in the child classes. If it's hard to you to extract it right away. just start from writing a child classes with full functionality (like I did with birds) and then, move the common staff into the base class.

wouldnt I make it whether I decide if the game is a team or individual game within the Sports Game class, along with if it can end in a tie?
How do you determine if a game can tie?

It's just a wild guess, but I assume, that the "canTie" parameter should be passed as a parameter, when you're creating an object. Applying to my example, it will be at the last step, when you're creating instances of a Sparrow and Penguin class.

The main question for me is what the difference between a Team game and the Individual, but it can be a part of a bigger assignment, and you'll add the other things at the next assignment.

What methods and varibles are needed in the Game class?

Not more, not less to produce the output, required by your class. Follow my sample and take a shot ;)

Ok. This is what I have done. I "think" it does everything the assignment asks.
First class

public class Game 
{
public static void main(String[] args) 
{
    Question39 gm1 = new Question39();

    System.out.println(gm1.toString());
}

public Game()
{

}  
}

Second

 public class Question39 extends Game 
{   
Scanner scan = new Scanner(System.in);
int players;
int tieNum;

public Question39()
{      
    super();
}     

 //Accessors (Getters)
public String getGameType() 
{
    System.out.println("Enter the total number of players");
    players = scan.nextInt();

    if (players > 2)
    {
        return "team";
    }    
    else if (players ==2)
    {
        return "individual";
    }
    else if (players ==1)
    {
        return "individual";
    }
    else
    {
         return "not";
    }        
}    

public String getCanTie()
{
    String canTie = "can";
    String cantTie = "can't";

    if (players >0)
    {
        System.out.println("Enter 1 for can tie / 2 for can't tie. ");
        tieNum = scan.nextInt();
    }

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

public String toString()
{
    return "This is a " + getGameType() 
            + " sport and " + getCanTie() + " end in a tie";
}
}

One observation:
A game either can or cannot end in a tie. That's a boolean condition, and the best way to implement it would be a boolean variable called soemthing like "canTie".
An int variable called "tieNum" will work, but anyone reading the code will have no idea what it is or how it works unless you all a load of comments. The well-named boolean is completely obvious.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.