0

I am given 4 classes, as follows.

public abstract class TennisPlayer{...}
public class GoodPlayer extends TennisPlayer{...}
public class WeakPlayer extends TennisPlayer{...}
public class Beginner extends WeakPlayer{...}

I am also given 3 declarations, as follows.

TennisPlayer g = new GoodPlayer("Sam");
TennisPlayer w = new WeakPlayer("Harry");
TennisPlayer b = new Beginner("Dick");

So my question is what would be the type for each object that is created above and why? For example the first statement, would Sam be type GoodPlayer or type TennisPlayer?

3 Answers3

1

The g would be of type GoodPlayer -- you can find this out by running g.getClass() which would give you GoodPlayer.class. However the declared type here is TennisPlayer which means you can only call methods declared on the TennisPlayer class or superclasses.

AlBlue
  • 23,254
  • 14
  • 71
  • 91
1

In this case, Sam would be a GoodPlayer type. You can initialize a variable, then instantiate with a child of that object. You can do this with interfaces as well, for example you can do Map sampleMap = new HashMap(); You can use the instanceOf method to verify this

    if (g instanceof GoodPlayer) {
        System.out.println("Sam is a GoodPlayer");
    }
1

Since the classes GoodPlayer, WeakPlayer, and Beginner extend the class Tennisplayer, they all inherit the properties of the TennisPlayer class. So, when you instantiate a variable such as...

Tennisplayer g = new GoodPlayer("Sam") ;

"Sam" is of type GoodPlayer but inherits the properties from the TennisPlayer class.

Since there can be so many types of tennis players, we can create child classes to extend the TennisPlayer class. However, all tennis players would have some property which is the same, such as height. So, we would define a variable for the height in the TennisPlayer class, and each child class will be able to implement that variable. We can make some properties exclusive to the child class. For example, the GoodPlayer might have properties that don't make sense for a WeakPlayer, or a Beginner to have.

This is simply polymorphism. You can find tons of information if you Google "Java polymorphism".

Saad
  • 175
  • 1
  • 15