Results 1 to 11 of 11
  1. #1
    Join Date
    Nov 2010
    Posts
    26
    Rep Power
    0

    Default Help with 2D Arrays of Objects - Static refs from non static method

    This is a little project I'm just doing myself, and I'm stuck.
    I'm basically trying to create a program, that, some time later, when I learn GUIs properly, will allow the user to play chess. For now, I'm just trying to set up the board and everything, but I'm having trouble with static (error I'm getting is non-static method cannot be referenced from a static context, or similiar), which we haven't really covered in class. Here's the relevant code:

    Java Code:
        public void printBoard()
        {
            for(int i=0; i<8; i++)
            {
                for(int j=0; j<8; j++)
                {
                    if(Piece.Board[i][j] == null)
                        System.out.print("  ");
                    else
                        System.out.print(Piece.getAbbrevType(getPieceOnPosition(i,j)));
                }
                System.out.println("");
            }
        }
    Basically I want to go through the array of Pieces (chess piece objects, taking a String type, int player, and then a position) and, if a piece doesn't occupy the space, then print out a space, otherwise, print out the first letter of the Type. From my limited understanding, the problem here is that I'm trying to make it generally take any Piece object, but because I have set it up as such, the Piece needs to be initialized before I can use it like this. Is this code salvagable? If so, can someone point me in the right direction? Thanks. Also, I have listed the rest of the code below, in case it's useful. Note that some of the methods under the pieces class may or may not be useful, I was experimenting with stuff and haven't gotten around to removing things that didn't. Edit: Could this be fixed by having get method below in red, getAbbrevType, ask for a row and column instead of a piece?

    Java Code:
        public Piece getPieceOnPosition(int row, int col){
            return Piece.Board[row-1][col-1];
        }
    
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    
    package chess;
    
    /**
    *
    * @author Rashmi
    */
    public class Piece{
        private String pieceType;
        private int owner;
        public static Piece[][] Board = new Piece[8][8];
        static int[] boardPosition = new int[2];
    
        public Piece(String type, int player, int row, int col){
            pieceType = type;
            owner = player;
            boardPosition[0] = row;
            boardPosition[1] = col;
        }
    
        public int getOwner(){
            return owner;
        }
    
        public String getType(){
            return pieceType;
        }
    
        [COLOR="Red"]public char getAbbrevType(Piece piece){
            if(piece == null){
                return ' ';
            }
            else
            {
                if(piece.getType().equalsIgnoreCase("Knight"))
                {
                    return 'N';
                }
                else
                {
                    return piece.getType().toUpperCase().charAt(0);
                }
            }
        }[/COLOR]
    
        public int getRow(){
            return boardPosition[0];
        }
        
        public int getCol(){
            return boardPosition[1];
        }
    
        public void placeOnBoard(Piece piece){
            Board[boardPosition[0]-1][boardPosition[1]-1] = piece;
        }
    
        public void autoPlace(String type, int player, int row, int col){
            Piece piece = new Piece(type, player, row, col);
            placeOnBoard(piece);
        }
    
        public boolean onBoardTest(Piece piece){
            if(Board[piece.getRow()][piece.getCol()] != null)
            {
                return true;
            }
            else return false;
        }
    
        public void move(int row, int col, Piece piece){
            int newRow, newCol;
            newRow = piece.getRow()+row;
            newCol = piece.getCol()+col;
            if(Board[newRow][newCol]==null && piece.onBoardTest(piece)==true){
                Board[piece.getRow()][piece.getCol()] = null;
                Board[newRow][newCol] = piece;
            }
        }
    
        public void capture(int row, int col, Piece piece){
            int newRow, newCol;
            newRow = piece.getRow()+row;
            newCol = piece.getCol()+col;
            if(Board[newRow][newCol]!=null && piece.onBoardTest(piece)==true){
               Board[piece.getRow()][piece.getCol()] = null;
                Board[newRow][newCol] = piece;
            }
        }
    }
    Last edited by Lord Voldemort; 12-31-2010 at 09:53 PM.

  2. #2
    Hibernate's Avatar
    Hibernate is offline Senior Member
    Join Date
    Dec 2010
    Location
    Stockholm, Sweden
    Posts
    222
    Blog Entries
    9
    Rep Power
    4

    Default

    If you have an instance of the class Piece, called piece.
    You can access its methods that do not have the 'static' modifier be typing
    piece.methodName()
    If you want to have a method that is called by typing
    Piece.methodName() rather then piece.methodName(),
    you must add the 'static' modifer to that method.
    Static methods can not access non-static methods and non-static variables without an instance of the class.

    Variables owned by instances must not have the 'static' modifier.
    Variables not owned by instances, but rather are shared for the entire program, must have the 'static' modifier.

    So your variables are correct, but methods like onBoardTest and other method that have a Piece parameter should be static.
    Last edited by Hibernate; 01-01-2011 at 03:37 AM.
    Ex animo! Hibernate
    Java, Arch Linux, C, GPL v3, Bash, Eclipse, Linux VT, GNOME 2 and many buttons on windows.

  3. #3
    Join Date
    Nov 2010
    Posts
    26
    Rep Power
    0

    Default

    Thanks so much.
    I definitely have a better idea of when or when not to use static.
    In retrospect, I guess I didn't really get my problem before I posted it, or else I just could have looked over some resources detailing static methods - however, I don't think that a lot of places put it as succulently as you have. Thanks again, and happy new year!

  4. #4
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Also note that static is a keyword that is to be evaded if possible. OOP relies on different objects communicating, so static methods should be used sparingly. One good application for them would be a utility class that deals with minutea like filling and displaying arrays etc.
    Also, I'd break down your Piece class into Piece and Board:
    Java Code:
    public class Piece {
      private int positionX, positionY;
      private String pieceType;
      private int owner;
      //constructors... methods...
    }
    and...
    Java Code:
    public class Board {
      private Piece[][] board;
      //constructors... methods...
    }
    Then, you also might want a utility class, that, for example, sets up the board in its starting position. You divide your methods like this to avoid clutter and improve readability. Since you won't need an instance of this utility class, using static methods is fine.
    Java Code:
    public class ChessUtil {
      public static Board startingPosition() {
        Piece[][] board = new Piece[8][8];
        board[1][1] = new Piece("pawn", 0); //if 0 is white
        ...
        ...
        return new Board(board);
      }
    }
    Note that ChessUtil is the only class that uses static methods.
    Another tip, I'd make the piece class abstract and use it as a super class for the pieces like this:
    Java Code:
    public abstract class Piece {
      //variables, constructors, methods...
      public abstract boolean validMove(int x, int y)
    }
    Java Code:
    public class Pawn extends Piece {
      //... ... ...
    }
    The good side of this style is the movement of the pieces. If you only have one piece class, you'd need to check the piece type to determine what moves it can make, this way, you can override the validMove() method for each class separately thus further reducing cluttering.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  5. #5
    Join Date
    Nov 2010
    Posts
    26
    Rep Power
    0

    Default

    Thanks for the tips! A few questions though.
    How does the static modifier hinder communication between classes?
    Also, wouldn't making the Piece class abstract make it like an interface for the subclasses? I was originally planning on setting the code up as you said, but I haven't learned Inheritance very well yet, apart from a quick look at an online tutorial (it's the next chapter in my book, which I don't have access to when I'm not at school :o), and the implementation was getting a bit tricky so I decided to try what I could. About the breaking up into two distinct classes, Piece and Board, thanks - I had just noticed yesterday that I had sort of blurred the line between the methods of Piece and things that related to the Board, but wasn't really sure how to organize this shift.

  6. #6
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Static doesn't hinder communication between classes, it hinders communication between objects, a very important difference.
    The reasons I made Piece abstract, since it's just a template for subclassing it will never be instantiated and secondly, you can add abstract methods to an abstract class, that is, a method without the definition, this way, all extending subclasses must define this method, and more importantly, since you will be storing every piece as a Piece class, it tells the compiler that this method can be used on a Piece object. Here's an example, copy and paste this into separate files, all must be in the same folder:
    Java Code:
    public abstract class A {
      public abstract void foo();
    }
    Java Code:
    public class B extends A {
      public void foo() {
        System.out.println("bar");
      }
    }
    Java Code:
    public class Tester {
      public static void main(String[] args) {
        A a = new B();
        a.foo();
      }
    }
    Then, comment the line public abstract void foo(); in A.java and try to compile again. This is the same principle which you would use in your chess program.
    Java Code:
    public abstract class Piece {
      //variables... methods...
      public abstract boolean validMove(int x, int y);
    }
    Java Code:
    public class Pawn extends Piece {
      public boolean validMove(int x, int y) {
        //determine if the piece can be moved to x,y coords
      } 
    }
    Java Code:
    public class Chess {
      Piece[][] board = new Piece[8][8];
      //game flow logic
      private void movePiece(int pieceX, int pieceY, int destX, int destY) {
        if(board[pieceX][pieceY].validMove(destX, destY))
          //...
      }
    }
    Last edited by m00nchile; 01-01-2011 at 08:14 PM.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  7. #7
    Join Date
    Nov 2010
    Posts
    26
    Rep Power
    0

    Default

    So basically, anything that is common to all pieces can be implemented in the parent class, but if it depends on the type of piece just leave abstract?

  8. #8
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Basically yes, a more understandable example would be this:
    Java Code:
    public abstract class Animal {
      public abstract void makeSound();
    }
    Java Code:
    public class Dog extends Animal {
      public void makeSound() {
        System.out.println("Woof");
      }
    }
    Java Code:
    public class Cat extends Animal {
      public void makeSound() {
        System.out.println("Meow");
      }
    }
    Having an abstract method in your parent class just tells you this method will be defined in all extending subclasses without defining it beforehand.
    Ever seen a dog chase its tail? Now that's an infinite loop.

  9. #9
    Join Date
    Nov 2010
    Posts
    26
    Rep Power
    0

    Default

    I looked around and can't figure out how to set up the constructor for subclasses.
    Online people said to do the equivalent of this:
    Java Code:
        public Rook(int player, int rowPos, int colPos){
            Piece piece = new Piece(player, rowPos, colPos);
        }
    but Rook is abstract.

  10. #10
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Rook should not be abstract, only Piece is abstract. Also, what you're trying to do is accomplished with the super keyword:
    Java Code:
    public class A {
      int a;
      public A(int a) {
        this.a = a;
      }
    }
    Java Code:
    public class B extends A {
      int b;
      public B(int a, int b) {
        super(a);
        this.b = b;
      }
    }
    Ever seen a dog chase its tail? Now that's an infinite loop.

  11. #11
    Join Date
    Nov 2010
    Posts
    26
    Rep Power
    0

    Default

    Thanks for all your help.
    I haven't had as much time to code now that school's started but progress is still being made, slowly.
    I've only got three big things left -
    Figuring out how to not allow pieces to go through each other, and making it so that the King can't go into check; for these I have a feeling that once I get one I'll be able to get the other, they seem somewhat similar. Finally, the GUIs and Mouse Events will take some figuring but I expect to be done by next week.

Similar Threads

  1. store array of arrays in array of arrays
    By joost_m in forum New To Java
    Replies: 4
    Last Post: 04-19-2010, 11:32 AM
  2. Arrays.sort... why sorting all arrays in class?
    By innspiron in forum New To Java
    Replies: 6
    Last Post: 03-23-2010, 02:40 AM
  3. Help with arrays
    By rp1783 in forum New To Java
    Replies: 5
    Last Post: 02-20-2010, 06:09 AM
  4. Arrays
    By tejens23 in forum New To Java
    Replies: 5
    Last Post: 11-25-2009, 11:46 PM
  5. need help with arrays
    By Jman in forum New To Java
    Replies: 17
    Last Post: 07-21-2008, 03:34 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •