Chapter 2: Object Orientation Flashcards
What is encapsulation?
Hiding implementation details, and only expose instance variables through public methods.
- protect instance variables
- make public accessor methods (getters/setters)
What is polymorphism?
You can treat any subclass as the superclass (or a interface). Every type in java is polymorphic because they can be treated as their own type as well as the Object type.
Describe a IS-A relationship
In java expressed using the extends and implements keyword (inheritance).
Car IS-A vechicle
Horse IS-A animal
Describe a HAS-A relationship
Whether a object has a reference to another object.
Car HAS-A engine
What is wrong?
class PlayerPiece extends GameShape, Animatable { }
A class can only extend a single class.
What are the 5 important rules for overriding methods?
- Argument list must exactly match
- Return type must be the same, or a subtype.
- The access level can be less restrictive
- Can only override non-final protected or public methods (or default if in the same package).
- You can’t introduce new exceptions in the throw clause, you can throw fewer exceptions.
Which overloaded method will be called? class Foo { public void doStuff(Animal a) {} // 1 public void doStuff(Horse a) {} // 2 }
Animal animal = new Horse(); new Foo().doStuff(animal);
doStuff(Animal a) will be called.
The reference type (not the object type) is used to determine which method is invoked.
What is overloading?
Adding a new method with the same name as an already existing method but with an different argument list
What is a downcast?
Casting a object down to a more specific type in the inheritance tree.
Dog d = (Dog) animal;
What is a upcast?
Casting a object to a more generic type in the inheritance tree.
Animal a = (Animal) dog;
Animal a = dog; // implicit cast
What is wrong? interface Pet { void foo(); } class Dog implements Pet { void foo() {} } class Beagle extends Dog implements Pet {}
Nothing. A subclass definining a interface that is already implemented by a superclass is perfectly fine.
True or False: A class can extend multiple classes
False
True or False:
A interface can extend multiple classes
False
True or False:
A interface can extend multiple interfaces
True
Finish the following senteces about return types:
- A overloaded method return type ….
- A overriden method return type ….
- Can be completely different from the original return type.
- Must be the same or a subclass of the original return type.