Jump to content

[Java] Calling a method in an extended class

So I'm making a game of chess and I've created a Piece class and then I have multiple extensions of the piece class for each individual piece. So say I have someting like this, how would I go about calling the method in the extended class? 

 

public abstract class Piece {

   public abstract boolean validMove(.......);

}

 


public class Rook extends Piece{

      public boolean validMove(.....){

            do stuff

      }

}

Piece newPiece = new Rook("white", 0, 0); //creates a rook at position 0,0 

if(_______.isValidMove(newPiece, destX, destY){ //should call Rook's validMove function if newPiece is a rook, or King's validMove if newPiece is a king, etc... 

    do stuff

}

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to comment
https://linustechtips.com/topic/656615-java-calling-a-method-in-an-extended-class/
Share on other sites

Link to post
Share on other sites

3 minutes ago, Mr_KoKa said:

So like this: (and leave everything else the same)

 


public class Rook extends Piece{

      public boolean validMove(.....){
            super.validMove();
            do stuff

      }

}

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to post
Share on other sites

Yes, but I guess you cannot forget to pass arguments as the class method that you inherit from has some marked by you with ....., so I guess it would look like this:

public class Rook extends Piece{

      public boolean validMove(.....){
            super.validMove(.....);
            do stuff

      }

}

P.S. Variables count doesn't need to match.

Link to post
Share on other sites

7 minutes ago, Mr_KoKa said:

Yes, but I guess you cannot forget to pass arguments as the class method that you inherit from has some marked by you with ....., so I guess it would look like this:

 

Okay, so I'm a bit unsure since it's supposed to return....

 

Is this how I would want it? Am I supposed to do anything with the isValid variable? 

public class Piece {

//should never be called
public boolean validMove(int destX, int destY, Piece[][] pieces, Piece activePiece) {

       return false; 

}
}


//in Rook extension of Piece

public boolean validMove(int destX, int destY, Piece[][] pieces, Piece activePiece){

          boolean isValid = super.validMove(destY, destY, pieces, activePiece);

          int deltaX = destX - this.x; 

          int deltaY = destY - this.y; 

          if(deltaX == 0 && deltaY == 0) //start = destination 

                   return false; 

          if(deltaX == 0 || deltaY == 0) {

                  if(checkPath(deltaX, deltaY, pieces))

                  return true;

          }

          return false; 

}

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to post
Share on other sites

If the isValid method of Piece should never be called and always returns false, the line 

boolean isValid = super.validMove(destY, destY, pieces, activePiece);

isn't needed, it doesn't do anything especially since you never use the return value.

1474412270.2748842

Link to post
Share on other sites

1 minute ago, fizzlesticks said:

If the isValid method of Piece should never be called and always returns false, the line 


boolean isValid = super.validMove(destY, destY, pieces, activePiece);

isn't needed, it doesn't do anything especially since you never use the return value.

It doesn't always return false. I just set the return value there to false since it's never called anyway (and if it is accidentally called, I definitely don't want it to return true). 

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to post
Share on other sites

44 minutes ago, Mr_KoKa said:

I read that page again, and if I call super.validMove(.....) from within the extended Rook class, then it will execute validMove in the Piece class -- that's not what I want? 

 

I want to call validMove from main, but I want to call the validMove that is associated with the class extension of the currently selected piece, not the generic validMove function that is in the Piece class.  

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to post
Share on other sites

2 minutes ago, djdwosk97 said:

I read that page again, and if I call super.validMove(.....) from within the extended Rook class, then it will execute validMove in the Piece class -- that's not what I want? 

 

I want to call validMove from main, but I want to call the validMove that is associated with the class extension of the currently selected piece, not the generic validMove function that is in the Piece class.  

Just call somePiece.validMove(), if it's a rook object it will call the rook's method, if it's a pawn it will call the pawn's method etc.

1474412270.2748842

Link to post
Share on other sites

7 minutes ago, fizzlesticks said:

Just call somePiece.validMove(), if it's a rook object it will call the rook's method, if it's a pawn it will call the pawn's method etc.

Well, I'm creating an array of Pieces and assigning a type of piece to specific points in the array. So if I were to call 


//MAIN

Piece[][] pieces = new Piece[8][8]; 

pieces[0][0] = new Rook(0,0); 

if(pieces[0][0].validMove(.....))

Then it tries to call the validMove function that's in the Piece class, and if there is no validMove function in the Piece class then it throws an error. 

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to post
Share on other sites

I don't know how, but when I'm trying this, it says "Extended class...".

//Base.class
public class Base {
    public boolean isValid(){
        System.out.println("Base class...");
        
        return false;
    }
}

//Extended.class
public class Extended extends Base {    
    public boolean isValid(){
        System.out.println("Extended class...");
        
        return true;
    }    
}

//Test.class
public class Test {
    public static void main(String[] args) {
        Base[][] array = new Base[2][2];
        array[0][0] = new Extended();
        array[0][0].isValid();
    }    
}

If it would work like you're saying I should get "Base class..."

Link to post
Share on other sites

7 minutes ago, Mr_KoKa said:

I don't know how, but when I'm trying this, it says "Extended class...".


//Base.class
public class Base {
    public boolean isValid(){
        System.out.println("Base class...");
        
        return false;
    }
}

//Extended.class
public class Extended extends Base {    
    public boolean isValid(){
        System.out.println("Extended class...");
        
        return true;
    }    
}

//Test.class
public class Test {
    public static void main(String[] args) throws InterruptedException {
        Base[][] array = new Base[2][2];
        array[0][0] = new Extended();
        array[0][0].isValid();
    }    
}

If it would work like you're saying I should get "Base class..."

Could it be because I'm creating my Piece array in a different function call? The function that builds the board (and places the pieces) will be called by main and then the move function (where the call to validMove resides) will be called from main. (I technically don't have a main method yet since I'm just setting up all my required classes).

 

 

 

 

*sigh* 

I missed the second ending parenthesis. I think I'm going to cry. Well, there goes like an hour of my life I'll never get back. 

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to post
Share on other sites

1 minute ago, djdwosk97 said:

Could it be because I'm creating my Piece array in a different function call? The function that builds the board (and places the pieces) will be called by main and then the move function (where the call to validMove resides) will be called from main. (I technically don't have a main method yet since I'm just setting up all my required classes).

That wouldn't make a difference. The only thing that would matter is if your functions have different parameters or return types which would prevent it from overriding the parent's function. Hard to help without seeing you're real code.

1474412270.2748842

Link to post
Share on other sites

Just now, fizzlesticks said:

That wouldn't make a difference. The only thing that would matter is if your functions have different parameters or return types which would prevent it from overriding the parent's function. Hard to help without seeing you're real code.

yeah, no, I just missed a second ending parenthesis and Eclipse decided to complain about everything except that (and since the whole line was marked with an error I didn't see the missing parenthesis). 

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to post
Share on other sites

@Mr_KoKa @fizzlesticks

 

Say I have a pieces array with an extended class object at each index. 


Piece[][] pieces = new Piece[8][8];

pieces[0][0] = new Rook(0,0);

Is there a way for me to quickly check to which class the piece at (0,0) belongs? (other than adding an identifying parameter to the rook class)

PSU Tier List | CoC

Gaming Build | FreeNAS Server

Spoiler

i5-4690k || Seidon 240m || GTX780 ACX || MSI Z97s SLI Plus || 8GB 2400mhz || 250GB 840 Evo || 1TB WD Blue || H440 (Black/Blue) || Windows 10 Pro || Dell P2414H & BenQ XL2411Z || Ducky Shine Mini || Logitech G502 Proteus Core

Spoiler

FreeNAS 9.3 - Stable || Xeon E3 1230v2 || Supermicro X9SCM-F || 32GB Crucial ECC DDR3 || 3x4TB WD Red (JBOD) || SYBA SI-PEX40064 sata controller || Corsair CX500m || NZXT Source 210.

Link to post
Share on other sites

You can call getClass().getSimpleName() on the object to get a string for the class name. Or you can use the "instanceof" operator. But using inheritance is meant to avoid this kind of thing, why do you need to know what class it is?

1474412270.2748842

Link to post
Share on other sites

Oh, I remember making a chess game a year or so ago. But I'm not sure how I did it...pretty sure I just used an array to store the table state and each value represented a different piece. Actually, let me find it. I'm curious.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to post
Share on other sites

@djdwosk97

7 hours ago, fizzlesticks said:

You can call getClass().getSimpleName() on the object to get a string for the class name. Or you can use the "instanceof" operator. But using inheritance is meant to avoid this kind of thing, why do you need to know what class it is?

This.  And it goes not just for Java, but for OOP in general.

 

Consider the following classes:

class A

class B extends A

class C extends A

 

 

If you declare your variable of type A, and anywhere (other than calling a constructor) care whether it is actually A, B, C, or really anything else that might inherent A (or implement A if it is an interface), then there is a very high chance your approach is fundamentally flawed.

There are occasional cases in some languages, for example if something (due to library design), must except type Object which then must be cast...but as a rule of thumb, if you care what the actual (as opposed to declared) class is you're probably doing it wrong.

Link to post
Share on other sites

On 09/08/2016 at 6:24 AM, djdwosk97 said:

So I'm making a game of chess and I've created a Piece class and then I have multiple extensions of the piece class for each individual piece. So say I have someting like this, how would I go about calling the method in the extended class? 

 


public abstract class Piece {

   public abstract boolean validMove(.......);

}

 


public class Rook extends Piece{

      public boolean validMove(.....){

            do stuff

      }

}


Piece newPiece = new Rook("white", 0, 0); //creates a rook at position 0,0 

if(_______.isValidMove(newPiece, destX, destY){ //should call Rook's validMove function if newPiece is a rook, or King's validMove if newPiece is a king, etc... 

    do stuff

}

Your super method is abstract so when you inherit the that class you have to give a body to the abstract method or call that class also abstract. When you call the isValid method be the reference be of the super class or base class it will call the base class method as your super class method is abstract. You can't not create an object of an abstract class.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×