Polymorphism
Polymorphism
The variable q knows less than the full story about the object to which it refers
1 import java.util.Scanner;
2
3 /**
4 This program shows a simple quiz with two question types.
5 */
6 public class QuestionDemo3
7 {
8 public static void main(String[] args)
9 {
10 Question first = new Question();
11 first.setText("Who was the inventor of Java?");
12 first.setAnswer("James Gosling");
13
14
ChoiceQuestion second = new ChoiceQuestion();
15
second.setText("In which country was the inventor of Java
16
born?"); second.addChoice("Australia", false);
17
second.addChoice("Canada", true);
18
second.addChoice("Denmark", false);
19
second.addChoice("United States",
20
false);
21
22 presentQuestion(first);
23 presentQuestion(second);
24 }
25
26 /**
27 Presents a question to the user and checks the response.
28 @param q the question
29 */
30 public static void presentQuestion(Question q)
31 {
32 q.display();
33 System.out.print("Your answer: ");
34 Scanner in = new Scanner(System.in);
35 String response = in.nextLine();
System.out.println(q.checkAnswer(response));
Program Run:
• Early Binding
• Overloaded methods/constructors
E.g., two constructors for BankAccount class
BankAccount() and BankAccount(double)
The compiler selects the correct constructor when
compiling the program by looking at the parameter
types.
account = new BankAccount(); //compiler selects BankAccount();
account = new BankAccount(1.00);//BankAccount(double)
The compiler can invoke the toString method, because it knows that every
object has a toString method:
Every class extends the Object class which declares toString
Overriding the t o S t r i n g Method
Object.toString prints class name and the hash code of the object:
BankAccount momsSavings = new BankAccount(5000);
String s = momsSavings.toString();
// Sets s to something like "BankAccount@d24606bf"
Override the toString method in your classes to yield a string that describes
the object’s state.
public String toString()
{
return "BankAccount[balance=" + balance + "]";
}
equals method checks whether two objects have the same content:
if (stamp1.equals(stamp2)) . . .
// Contents are the same
== operator tests whether two references are identical - referring to the same
object:
if (stamp1 == stamp2) . . .
// Objects are the same
Overriding the e q u a l s Method
The equals method can access the instance variables of any Stamp object.
The access other.color is legal.
The i n s t a n c e o f Operator
It is legal to store a subclass reference in a superclass variable:
ChoiceQuestion cq = new ChoiceQuestion();
Question q = cq; // OK
Object obj = cq; // OK