简体   繁体   中英

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().

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
        }
    }

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();
}

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(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM