Home>

The following program is an excerpt from "Clearly understand java practice" p131.

Output result (book description)
Equipment: Steel sword * Question
Clone with clone ()
Change the name of the sword of the hero who copied it
Shows the equipment of the hero of the copy source and copy destination
Copy source: Hinoki stick/Copy destination: Hinoki stick

Why is it "equipment: steel sword" even though the method is called with getName ()?

public class Main {
    public static void main (String [] args) {
        Hero h1 = new Hero ("Minato");
        Sword s = new Sword ("Sword of Steel");
H1.setSword (s);
        System.out.println ("Equipment:" + h1.getSword (). GetName ());
        System.out.println ("duplicate with clone ()");
        Hero h2 = h1.clone ();/* Duplicate here * /
        System.out.println ("Rename the original hero's sword");
        h1.getSword (). setName ("Hinoki cypress stick");
        System.out.println ("Shows source and destination hero equipment");
        System.out.println ("copy source:" + h1.getSword (). getName () +
        "/ Copy to:" + h2.getSword (). getName ());
    }
}
public class Hero implements Cloneable {
    String name;// name
    int hp;// HP
    Sword sword;// Equipped weapon
    public Hero clone () {
        Hero result = new Hero (name);
        result.name = this.name;
        result.hp = this.hp;
        result.sword = this.sword;
        return result;
    }
    public Hero (String name) {
        this.name = name;
    }
    public Sword getSword () {
        return sword;
    }
    public void setSword (Sword sword) {
        this.sword = sword;
    }
    public String getName () {
        return name;
    }
    public void setName (String name) {
        this.name = name;
    }
}
public class Sword {
    private String name;
    public Sword (String name) {
        this.name = name;
    }
    public String getName () {
        return name;
    }
    public void setName (String name) {
        this.name = name;
    }
}
  • Answer # 1

    Why is the return value (minato) of getName () not output in h1.getSword (). getName ()?

    Minato is for h1.getNmae ().

    Sword s = new Sword ("Sword of Steel");
    h1.setSword (s);

    Because there is

    System.out.println ("Equipment:" + h1.getSword (). GetName ());

    Is

    s = h1.getSword ();
    System.out.println ("Equipment:" + s.getName ());

    Will be the same as.

  • Answer # 2

    I'm not sure from the point of view of the question, but do you set it in advance?

          Sword s = new Sword ("Sword of Steel");
    H1.setSword (s);
            System.out.println ("Equipment:" + h1.getSword (). GetName ());

Trends