The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Class heirarchy

Hello

So i'm here again posting some questions about a simple 2-player chess engine that I'm making.
I have a question regarding classes and sub-classes. It requires some explanation of the workings so please bear with me.

My structure is as follows:

I have a class called ChessGame in which resides the main array of the piece positions and the computations of the game like if the move of the piece is legitimate etc.
I have a class which is called ChessPiece , and I have a class for each of the pieces : King , Queen etc... which extend ChessPiece.

The main array which holds the positions of the pieces is of type : ChessPiece . Basically what I want is for that array to hold the INSTANCES of each piece that is on the board . And 'null' if the square is
empty.

The array shows the initial position of the pieces as generated at the beginning of the game.

My question is : How can I access the methods and variables of the instances of the pieces?
At the beginning of the program I create a new instance of the ChessGame class

ChessGame gameState; // Global declaration in the Interface class

gameState = new ChessGame(); // initialisation in the constructor of the Interface class

Then in the ChessGame class I declare and initialise all of the instances of each piece.

Why can't I do something like :

gameState.ChessBoard[2][4].getColor();

?

I've tried creating an instance of ChessPiece in the ChessGame class and declaring the pieces themselves in the ChessPiece class and then trying something like

gameState.chessP.kingWhite.getColor();

but that gives me a stack overflow error because the contructor in ChessPiece is called everytime an instance of the Piece is created and it basically loops.

Can someone advise me how I can structure this?
What I basically want to do is have an array of Instances of all the pieces in the ChessGame class.
The reason I'm having this issue is because every diffrent piece type (king , queen etc) is in it's own class
that's why I made the Chesspiece Class so I could put all the pieces under one 'type' .
So how does one go about working with this kind of thing?

Re: Class heirarchy

There is no recursion. I don't know why it loops , but I know that everytime an instance of a King for example is called , then the constructor of the ChessPiece class is called.
I know this from adding a println statement to the constructor of ChessPiece and seeing it be called 32 times.
If I Just create an instance of ChessGame and from there create the instances of the pieces themselves then it's fine but i can't access the methods/variables through ChessGame -> ChessPiece -> king.getColor() for example.
If I create an stance of ChessGame which creates an instance of ChessPiece which create the instances of the pieces themselves then I get a stack overflow error.The reason I want to create the instances of the pieces through the ChessPiece umbrella class is so that I can put instances of those pieces in a "ChessPiece" type array and use them as my main board.
If there is a better way of doing it then I'm all ears.

If you do not understand then please do ask , I will try to make clearer my purpose as I'm pretty stumped here and would like some consultation.

Re: Class heirarchy

A Game class creating an array of ChessPieces and filling it with pieces makes sense.

Well yes , but how do I access functions and variables inside the classes?
Lets say we have the following instances:
ChessGame newGame;
ChessPiece newSet;
King whiteKing;

and my array is of type ChessPiece.
I want to access variables/methods from whiteKing.
For some reason it doesn't work if I do ChessPiece[0][4].getColor();
Am I doing it wrong?
A colleague of mine suggest I use an abstract class type but I don't know how to implement that

Re: Class heirarchy

Your colleague is suggesting that ChessPiece should be abstract. Abstract classes cannot be initialized, so you cannot create any "ChessPiece" objects. This would be correct, since you don't want "ChessPiece" objects, you want "King" objects, "Queen" objects, ect.

Well yes , but how do I access functions and variables inside the classes?
Lets say we have the following instances:
ChessGame newGame;
ChessPiece newSet;
King whiteKing;
and my array is of type ChessPiece.
I want to access variables/methods from whiteKing.
For some reason it doesn't work if I do ChessPiece[0][4].getColor();

Have you initialized the whiteKing object? If you are getting a null pointer exception, it would probably be because you haven't initialized the object yet.

NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

When asking for help, please follow these guidelines to receive better and more prompt help:
1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
2. Give full details of errors and provide us with as much information about the situation as possible.
3. Give us an example of what the output should look like when done correctly.

Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

but when I run it it gives me a Nullpointer exception. I don't know why , I initialised the pieces as you can see in my code above.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Chess_contents.ChessGame.getInfo(ChessGame.java:17 0)
at Chess_contents.ChessGame.Square_pressed(ChessGame. java:184)
at Chess_contents.Interface.mousePressed(Interface.ja va:214)
at java.awt.Component.processMouseEvent(Component.jav a:6502)
at javax.swing.JComponent.processMouseEvent(JComponen t.java:3320)
at java.awt.Component.processEvent(Component.java:627 0)
at java.awt.Container.processEvent(Container.java:222 9)
at java.awt.Component.dispatchEventImpl(Component.jav a:4861)
at java.awt.Container.dispatchEventImpl(Container.jav a:2287)
at java.awt.Component.dispatchEvent(Component.java:46 87)
at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4489)
at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4422)
at java.awt.Container.dispatchEventImpl(Container.jav a:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719 )
at java.awt.Component.dispatchEvent(Component.java:46 87)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:735)
at java.awt.EventQueue.access$200(EventQueue.java:103 )
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java: 705)
at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:91)

Re: Class heirarchy

it says symbol not found

You need to copy the full text of the error message and paste it here. What you posted left out what symbol was not found.
Please copy full text of the compiler's error message and paste it here.
The message should show the source with a ^ under the location of the error.
Here is a sample from the javac compiler:

Re: Class heirarchy

Ok, I understand your problem.
Your ChessPiece array contains implemented subclasses of ChessPiece, but the "type" of the array is ultimately: ChessPiece. This means that the only methods and variables you can access for the subclasses you pull from the ChessPiece array (without casting) are the ones declared in the ChessPiece class. The availability of the methods and variables are determined at compile-time. However, the implementation of the method will be determined at runtime, based on which subclass of ChessPiece the object really is (the compiler has no idea what type of ChessPiece it is, it just knows that it's a ChessPiece or a subclass of ChessPiece).
Every ChessPiece should have a color, correct? So that method should exist in the ChessPiece class. But what if we want to implement the getColor() method differently for each subclass of ChessPiece? The subclasses can override the method and implement it their way. It will all get sorted out at runtime.
Do you understand that much?

NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

When asking for help, please follow these guidelines to receive better and more prompt help:
1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
2. Give full details of errors and provide us with as much information about the situation as possible.
3. Give us an example of what the output should look like when done correctly.

Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Re: Class heirarchy

The ChessPiece class has no methods. The code you posted uses the currentBoard which is type ChessPiece. currentBoard has no methods that can be used.

If ChessPiece were abstract and had all the common methods as abstract then that code should work.

Yes I understand this , please read the last edit to my last post where I try to make the ChessPiece class abstract and add the methods which all the subclasses contain into it. It gives me a nullpointer exception at runtime . I pasted the error code.

Ok, I understand your problem.
Your ChessPiece array contains implemented subclasses of ChessPiece, but the "type" of the array is ultimately: ChessPiece. This means that the only methods and variables you can access for the subclasses you pull from the ChessPiece array (without casting) are the ones declared in the ChessPiece class. The availability of the methods and variables are determined at compile-time. However, the implementation of the method will be determined at runtime, based on which subclass of ChessPiece the object really is (the compiler has no idea what type of ChessPiece it is, it just knows that it's a ChessPiece or a subclass of ChessPiece).
Every ChessPiece should have a color, correct? So that method should exist in the ChessPiece class. But what if we want to implement the getColor() method differently for each subclass of ChessPiece? The subclasses can override the method and implement it their way. It will all get sorted out at runtime.
Do you understand that much?

I do understand almost all of what you are saying .
So basically what you are saying is that I should copy all the methods that are in the subclasses into the ChessPiece class and when I call them the methods in the subclasses will override them
because even though the array is of type ChessPiece , the objects inside it are of another class type ?

--- Update ---

aussiemcgr I tried to implement the method getColor() for example in the ChessPiece class but I still get that nullpointerexception that I posted above.

Re: Class heirarchy

I do understand almost all of what you are saying .
So basically what you are saying is that I should copy all the methods that are in the subclasses into the ChessPiece class and when I call them the methods in the subclasses will override them
because even though the array is of type ChessPiece , the objects inside it are of another class type ?

Pretty much. If you wanted to make ChessPiece abstract, you could do this without actually implementing the methods in the ChessPiece class.
For example of how abstract and overriding methods work:

The objects array holds objects of type: A. But this includes all subclasses of A too. So since the getNumber() method is declared in the A class, we can call objects[i].getNumber() without getting a compile error. However, the value that method returns is determined by which subclass of A is in that index of the array, which is not determined until runtime.

--- Update ---

aussiemcgr I tried to implement the method getColor() for example in the ChessPiece class but I still get that nullpointerexception that I posted above.

Before calling the getColor() method, check if the item in the index is null. Keep in mind that you do have null indexes in your array. You cannot call the getColor() method (or any method) on a null reference.

NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

When asking for help, please follow these guidelines to receive better and more prompt help:
1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
2. Give full details of errors and provide us with as much information about the situation as possible.
3. Give us an example of what the output should look like when done correctly.

Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Aha yes , I checked and it is indeed null on the currentBoard[0][0] (an instance of Rook is supposed to be there) but I can't understand why It's null .
I initialised it before that . Could you check my code above (class ChessGame) and see what I'm doing wrong?
I'd be very gratefull.

Re: Class heirarchy

If you are putting it directly into your ChessPiece array, it makes no difference.

The second one is useful if you plan on directly using the pawn1Black object, and you are wanting to call methods which are only found in the Pawn class (and not found in the ChessPiece class). But if you are adding it to the ChessPiece array and then pulling the object out of the array before using it, the object which comes out of the array will always be of type: ChessPiece (as far as the compiler is concerned, runtime knows it's "real" type), so you only have access to methods declared in the ChessPiece's anyway.

NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

When asking for help, please follow these guidelines to receive better and more prompt help:
1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
2. Give full details of errors and provide us with as much information about the situation as possible.
3. Give us an example of what the output should look like when done correctly.

Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/