Web Analytics Made Easy -
StatCounter Java - Abstract Classes, Abstract Methods - CodingForum

Announcement

Collapse
No announcement yet.

Java - Abstract Classes, Abstract Methods

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Java - Abstract Classes, Abstract Methods

    I am confused about abstract classes and abstract methods

    In Java, it is possible to create superclasses which enable its subclasses to access its methods (if the methods are protected or public). The use of a superclass is that it lessens the amount of code in the subclasses since you can put the very similar methods that the subclasses have in common into one class, which they can all access.

    You can then make the superclass abstract, but then that defeats the point of having the superclass. If the superclass is abstract then you can create abstract methods. The abstract methods ensure that the subclasses have those methods implemented in their class, which seems good. However, as I said before, if the subclasses have very similar methods then wouldn't you want the superclass to hold this method rather than enforce it on each of them. This seems to confuse me greatly.

    Can anyone shed some light on the topic?

  • #2
    The point is to force subclasses to override a certain method, but each subclass can define their own way of implementing that method.

    For example, say you're creating a chess game. You will have different chess pieces, like a rook and a bishop. Both pieces should check whether they can move to the selected square, but each one has a different check based on their allowed movements.

    So, you'll set something up like:
    Code:
    public abstract class ChessPiece
    {
        // Constructor, variables, etc.
        protected int currX;
        protected int currY;
    
        public ChessPiece(int x, int y)
        {
             this.currX = x;
             this.currY = y;
        }
    
        public int getXPos()
        {
            return this.currX;
        }
    
        public int getYPos()
        {
            return this.currY;
        }
    
        public void setPosition(int x, int y)
        {
            this.currX = x;
            this.currY = y;
        }
    
        // Return true or false based on whether chess piece can move to square
        public abstract boolean canMovePiece(int x, int y);
    }
    
    public class Rook extends ChessPiece
    {
        // Constructor, variables, etc.
        public Rook(int x, int y)
        {
            super(x, y);
        }
    
        public boolean canMovePiece(int x, int y)
        {
            if((this.currX == x) || (this.currY == y))
                return true;
            else
                return false;
        }
    }
    
    public class Bishop extends ChessPiece
    {
        // Constructor, variables, etc.
    
        public boolean canMovePiece(int x, int y)
        {
            if((this.currX - x) == (this.currY - y))
                return true;
            else
                return false;
        }
    }
    Now, obviously, these methods don't totally work, as they don't account for objects that may be in the way or the sides of the board, but you get the idea.

    Creating the abstract class and method ensures that all game pieces override and utilize the canMovePiece method. This allows for greater scalability, easier future development, less obfuscated code, and less debugging errors that could be created by the previous three.

    However, as you are aware, if the method is going to be implemented the same for all subclasses, then create a non-abstract method in the parent (super-) class that all child (sub-) classes will inherit.

    -Shane
    Last edited by TheShaner; Apr 8, 2009, 02:43 PM. Reason: Updated code

    Comment


    • #3
      Thanks for the response, but to add to the problem, what if another concrete class needs to call a method from the abstract class?

      Take the abstract method you have used named 'canMovePiece', and say it needs to be used by a different class; perhaps named 'GameBoard', which needs to check whether the chess piece can be moved. Because the class holding that method is abstract you can't call its method, so how would you overcome this?

      Comment


      • #4
        Originally posted by webguy08 View Post
        Take the abstract method you have used named 'canMovePiece', and say it needs to be used by a different class; perhaps named 'GameBoard', which needs to check whether the chess piece can be moved. Because the class holding that method is abstract you can't call its method, so how would you overcome this?
        Classes can only use each others' method and variables if they are within each others' scope and have a parent-child relationship, whether it's abstract or not.

        In my previous example, Rook and Bishop cannot use each others' methods whether they're public or not, or abstract or not. If you had a GameBoard class, you could have a method that accepts a ChessPiece object, i.e. a Rook, which could implement its own canMovePiece method.

        Example:
        Code:
        public class GameBoard
        {
            // Variables and constructors
        
            public boolean movePiece(ChessPiece piece, int x, int y)
            {
                if(piece.canMovePiece(x, y))
                {
                    piece.setPosition(x, y); // public method in ChessPiece class
                    return true;
                }
                else
                    return false;
            }
        }
        Code:
        // Somewhere in your main class
        GameBoard gb = new GameBoard();
        Rook rook1_black = new Rook();
        // more stuff
        if(gb.movePiece(rook1_black, 0, 4)) 
            System.out.println("Rook 1 Black has been moved.");
        else
            System.out.println("You cannot move Rook 1 Black there.");
        Does that answer your question?

        -Shane
        Last edited by TheShaner; Apr 8, 2009, 02:39 PM.

        Comment


        • #5
          So you can call methods in abstract classes without having to create an instance of it?

          Comment


          • #6
            Originally posted by webguy08 View Post
            So you can call methods in abstract classes without having to create an instance of it?
            No, you cannot. However, when you instantiate a Rook object, you're gaining access to not only Rook methods, but your ChessPiece methods. All abstract does is force the child classes to define how the method works, while the parent just says, "This is what it should be called, parameters it should accept, and value it should return. I don't care how you implement it." This is different from a regular public method in the parent class since a regular public method just says, "Hey, here's a method you can use. If you want to override it, it's your choice. I don't care."

            And sorry, I may have created a little confusion with this line:
            Code:
            piece.setPosition(x, y); // abstract method in ChessPiece class
            The above should be a regular public method in the ChessPiece class because there wouldn't be any difference between a Rook and Bishop when setting the position. I've changed it in my post now. Check out the updated code in my first post. In the ChessPiece class, you will now see regular getter and setter methods that all children classes can use, along with an abstract method that all children must define.

            -Shane
            Last edited by TheShaner; Apr 8, 2009, 02:46 PM.

            Comment

            Working...
            X