Polymorphism, overriding, overloading
Declared type and actual type, dynamic dispatch, overriding an inherited method, overloading by signature, calling super.method(), casting and type testing in Java.
- 26 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
A few cards from the deck
Polymorphism: what is it?
Show the answer
The ability of one method call to produce different behaviours depending on the actual class of the object that receives it.
A loop calling
speak()on an array of animals does not need to know which are dogs or cats: each object answers in its own way.What does this loop print?
```java
class Animal {
void speak() { System.out.println("..."); }
}
class Dog extends Animal {
void speak() { System.out.println("Woof"); }
}
class Cat extends Animal {
void speak() { System.out.println("Meow"); }
}
Animal[] t = { new Dog(), new Cat(), new Animal() };
for (Animal x : t) {
x.speak();
}`Woof,Meow,......,...,...Woof,Woof,...Meow,Woof,...
Show the answer
Woof,Meow,...The variable
xis always of type Animal, but the call is resolved at run time from the actual object: Dog, then Cat, then Animal.An overriding method keeps the same … as the inherited method; the … annotation has the compiler check this rule.
Show the answer
An overriding method keeps the same signature as the inherited method; the @Override annotation has the compiler check this rule.
Without the annotation, a typo in a parameter type silently creates a new method. With it, the error is reported:
method does not override or implement a method from a supertype.Overriding: what is it?
Show the answer
Rewriting, in a subclass, an inherited method with the same signature, to change its behaviour.
The parameters must be identical, otherwise you write another method. The
@Overrideannotation has the compiler check this.This program compiles, but
l.contains(new Point(1))printsfalsealthough the list holds a point with x equal to 1. Why?
```java
class Point {
int x;
Point(int x) { this.x = x; }
public boolean equals(Point p) { return p.x == x; }
}
List<Point> l = new ArrayList<>();
l.add(new Point(1));
System.out.println(l.contains(new Point(1)));`containscompares references with==and never callsequalsequals(Point)overloadsequals(Object)without overriding ithashCodeis missing, andcontainschecks it beforeequals- The
xattribute should be declaredprivate
Show the answer
equals(Point)overloadsequals(Object)without overriding itcontainscallsequals(Object). The method written here takes a Point: another signature, so an overload that is ignored. With@Overridethe compiler would have rejected it; the right form takes anObject. AnArrayListdoes not look athashCode; only hash tables do.