View Full Version : Extend Multiple Objects

12-04-2011, 09:54 PM
Hello everyone, please help me out, I'm tearing my hair out!

I have three classes; Human, Player and Hunter.

The Human has attributes x, y and state, plus various methods, and I want the Player and Hunter to inherit these attributes and methods.

My program prints a grid with the positions of the Player and the Hunters (x and y being their respective co-ordinates). Is there any way I can have the Player and Hunter extend Human but retain separate attributes?

For example, I create a Player object and a Hunter object. Right now, x = 0 and y = 0 for them both. If I move the Player to the right, x = 1 for them both, but I only want x = 1 for the Player, I still want x = 0 for the Hunter. Does that make sense?

Here is the relevant code:

Player player = new Player(); // create Player
Hunter[] hunter = new Hunter[5]; // allocates memory for 5 Hunters

for (int i = 0; i < 5; i++) {
hunter[i] = new Hunter();

public class Human
private int x;
private int y;
private int state;

public class Player extends Human

public class Hunter extends Human


So what can I change to have different x and y co-ordinates for each instance of each class?

Thanks in advance!

12-04-2011, 10:30 PM
My apologies- Java DOES have unique attributes for each new object you create. My problem was in my coding. All fixed now :)

12-04-2011, 10:32 PM
It already does that. Human has x, y and state listed as instance variables. Any object created off of this class or derived class will treat them independent of any other variable. Player and Hunter do not share the same x, y, and state as each other.
It should be noted that with just properties you have no way of actually setting the variables though, as private will deny the ability for extended classes to set the properties. Either use protected or make sure you have mutators in place.
For a quick example, I simply used:

public class Human
protected int x, y, state;

public String toString()
StringBuilder sb = new StringBuilder(this.getClass().getSimpleName() + "[");
sb.append("x=" + x);
sb.append(", y=" + y);
sb.append(", state=" + state);
return sb.toString();

With blank extensions, and a tester which I threw into scope of Human:

public static void main(String... argv)
Player p = new Player();
Hunter[] h = new Hunter[5];
for (int i = 0; i < 5; ++i)
h[i] = new Hunter();

p.x = 1;
System.out.println("Player: " + p);
Random r = new Random();

for (int i = 0; i < h.length; ++i)
h[i].x = r.nextInt(50);
h[i].y = r.nextInt(3);
System.out.println("Hunter(" + i + "): " + h[i]);

Results in:

Player: Player[x=1, y=0, state=0]
Hunter(0): Hunter[x=41, y=2, state=0]
Hunter(1): Hunter[x=9, y=1, state=0]
Hunter(2): Hunter[x=9, y=2, state=0]
Hunter(3): Hunter[x=31, y=1, state=0]
Hunter(4): Hunter[x=6, y=0, state=0]

Which is expected.