Inheritance:
- Uses
extends. Java allows single inheritance only. - Every class ultimately extends
Object. This provides thetoString,equals,hasCode,clone, andgetClassmethods. - Inheritance means ‘is-a’ relationship. (Car and SteeringWheel have a ‘has a’ relationship, so thats not inheritance, that is composition)
Overriding vs Overloading:
- Overriding uses the same signature in a subclass and replace the inherited method. you can still call the original method using
super.method(). - uses the same name but with different parameters. the subclass has both versions.
Constructor chaining:
super(...)must be the first line of a constructor. if you don’t write itsuper()will be automatically added by java.- If the parent has no no-arg constructor, the implicit call is a compile error.
- Constructor execute in order Object -> parent -> child.
Access modifiers:
private: class only- default (package): the same package
protected: the same package + subclassespublic: everywhere
final: a final class can’t be extended, and a final method can’t be overridden.
Upcasting:
Animal a = new Dog();
- You can call methods that exits in the reference type, so
p.getID()fails to compile ifPersonlacksgetID(). To make a method in the class Person differ between a Student and a Professor we override the method in each subclass. - Dynamic binding runs the object’s version of an overridden method at runtime.
- Polymorphism = upcasting + dynamic binding.
what doesn’t have polymorphism: static, private, and final methods are resolved at compile time.
equals() trap:
equals(Point p)is an overload.euqals(Object o)overrides it.
the standard steps are: self check, null check, intanceof check, downcast, then compare fields.
Abstract class:
- it can’t be instantiated and may mix abstract and concrete methods.
- Any class with an abstract method must be declared as abstract. (reverse isn’t required)