dimanche 2 avril 2017

Class reference vs. interface reference [duplicate]

This question already has an answer here:

What is better approach? Program to an interface and in case of using method which is not a part of interface then cast type of that particular class when calling that method or save class instance to class reference?

I have this example:

Abstract class:

public abstract class AbstractFighter implements IBehavior {

    private final String name;
    private int strength;

    public AbstractFighter(String name, int Strength) {
        this.name = name;
        this.strength = strength;
    }

    public String getName() {
        return name;
    }   

    public int getStrength() {
        return strength;
    }
    public void setStrength(int strength) {
        this.strength = strength;
    }
}

Interface:

public interface IBehavior {
    public String hit();
}

Two implementations:

//this class only uses method from interface
public class Warrior extends AbstractFighter {

    public Warrior(String name, int strength) {
        super(name, strength);
    }

    @Override
    public String hit() {
        return (getName() + ":I hit you with " + getStrength() + " points.");
    }
}

//this class have one more method
public class Wizard extends AbstractFighter {

    private int spellStrength;

    public Wizard(String name, int Strength, int spellStrength) {
        super(name, Strength);
        this.spellStrength = spellStrength;
    }

    @Override
    public String hit() {
        return (getName() + ":I hit you with " + getStrength() + " points.");
    }

    public String magicalHit() {
        return (getName() + ":I hit you with " + spellStrength + " points.");
    }
}

Main class:

public class Main {

    public static void main(String[] args) {

        IBehavior swordsMan = new Warrior("Boromir", 3);

        //first example
        IBehavior wizard = new Wizard("Gandalf", 2, 4);     
        System.out.println(((Wizard)wizard).magicalHit()); // i have to mention subclass

        //second example
        Wizard wizard2 = new Wizard("Saruman", 1, 5);
        System.out.println(wizard2.magicalHit());
    }
}

Aucun commentaire:

Enregistrer un commentaire