I've got a problem with exercise in Java Head First. Basically I don't understand why output changes based on frighten's methode argument. I don't get what impact on output have values returned by classes Dragon, Vampire and Monster.
public class MonsterTestDrive {
public static void main(String [] args) {
Monster [] ma = new Monster[3];
ma[0] = new Vampire();
ma[1] = new Dragon();
ma[2] = new Monster();
for(int x = 0; x < 3; x++) {
ma[x].frighten(x);
}
}
}
class Monster {
// A
}
class Vampire extends Monster {
// B
}
class Dragon extends Monster {
boolean frighten(int degree) {
System.out.println(“breath fire”);
return true;
}
}
Which of the A-B pairs of methods listed on the right, if inserted into the classes on the left, would compile and produce the output shown?
(The A method inserted into class Monster, the B method inserted into class Vampire.)
//1
boolean frighten(int d) {
System.out.println(“arrrgh”); //A
return true;
}
boolean frighten(int x) {
System.out.println(“a bite?”);//B
return false;
}
//2
boolean frighten(int x) {
System.out.println(“arrrgh”);//A
return true;
}
int frighten(int f) {
System.out.println(“a bite?”);//B
return 1;
}
//3
boolean frighten(int x) {
System.out.println(“arrrgh”); //A
return false;
}
boolean scare(int x) {
System.out.println(“a bite?”);//B
return true;
}
//4
boolean frighten(int z) {
System.out.println(“arrrgh”);//A
return true;
}
boolean frighten(byte b) {
System.out.println(“a bite?”);//B
return true;
}
1 is the answer.
Look at the method signature of frighten method in Dragon class. It takes integer as input and returns boolean as output. So, the "frighten" of the parent class (Monster) must also have the same method signature.
boolean frighten(int d) {
System.out.println(“arrrgh”); //A
return true;
}
Now, since the Vampire class is extending the Monster class and it is expected to override the frighten method, it should also have the same method signature and same name.
boolean frighten(int x) {
System.out.println(“a bite?”);//B
return false;
}