GoingWild
GoingWild

Reputation: 82

Calling method of subclass from superclass

I have a class "Tool" and various subclasses like "Axe" oder "Hammer". Each kind of Tool(Axe, Hammer) has at least one method which is defined in the subclass. And there is a "Worker" class with a slot for one tool at the time that can be every tool.

Tool class:

public abstract class Tool {

    private double durability;

    public double getDurability() {
        return durability;
    }

    public void setDurability(double durability) {
        this.durability = durability;
    }
}

Axe class:

public class Axe extends Tool {

    public void chop() {
        //chop some wood
    }
}

Now to set one tool for the worker:

Tool tool = new Axe();

The problem is that when i call "axe." i get getDurability() and setDurability() but not chop().

Upvotes: 0

Views: 88

Answers (3)

Bhaskar
Bhaskar

Reputation: 7523

abstract class Tool {

    private double durability;

    public double getDurability() {
        return durability;
    }

    public void setDurability(double durability) {
        this.durability = durability;
    }

    public void work(){

    }
}




class Axe extends Tool {

        @Override
        public void work() {
            this.chop();
        }

        public void chop() {
            //chop some wood
        }
    }

Upvotes: 4

Thilo
Thilo

Reputation: 262474

If you want to call chop, you need to know that you have an Axe (not just any old Tool). Then you can typecast:

Axe axe = (Axe) tool;
axe.chop();

If you are not sure if this is really an Axe, you can check first (but this is a bit of a design smell):

if (tool instanceof Axe){
  Axe axe = (Axe) tool;
  axe.chop();
}

Upvotes: 1

Faisal Ali
Faisal Ali

Reputation: 1135

You have to call after casting to Axe

((Axe)tool).chop();

But you have to check it before casting to avoid any Exception

if (tool instanceof Axe) { 
    ((Axe)tool).chop(); 
}

Upvotes: 0

Related Questions