Contracts between classes and ways to hide them.
Key points, notes and past questions
OOP: Inheritance, Polymorphism, Interfaces and Inner Classes
Which method runs and what compiles: the base for most other topics.
- Constructors and super
- One
new, one object, several constructors. - The first line is
this(...)orsuper(...); with neither, the compiler addssuper();. - Bodies finish parent first, child last.
- A child fills a parent's private field only through a parent constructor or method.
- One
- Override or overload?
- Signature means name plus parameter types.
- Overload is decided by written types at compile time.
- Override is decided by the object's class at run time.
@Overrideturns a silent overload into a compile error.
- Dynamic dispatch
- Name check: static type. Body choice: runtime class.
- A call inside a parent method still dispatches on
this. - Fields and
staticmethods follow the static type. - A parent variable cannot call a child-only method.
- final and private
finalmethod: visible, not replaceable.privatemember: invisible to the child.- A same-named child method beside a private parent method is a new method.
finalreference: the arrow is fixed, the object is not.
- toString and equals
- Header:
public String toString(), and it returns the text. - Header:
public boolean equals(Object o). - Inside
equals: test, cast, compare. ==compares objects' identity;equalsis whatever you wrote.
- Header:
- Static type, casts and instanceof
- The static type decides what may be called.
- A cast to a related type compiles and is checked at run time.
- A failed check throws
ClassCastException. instanceofisfalsefornullandtruefor subclasses and implementers.
- Abstract classes and interfaces
- A creatable class has a body for every inherited method.
defaultis inherited;staticis called asInterface.name().- Equal defaults from two unrelated interfaces: the class must override.
- Class method beats default, with no error.
- Callbacks and private inner classes
- A callback is a call through a stored interface reference.
- The caller pauses until the callback returns.
- A private inner class is usable outside only through a visible type.
- An inner class can read the outer object's private fields.
Notes23 past questions in this topic
Week 3: Inheritance, polymorphism, class hierarchy, modifiersWeek 5: Generic programming, subtyping, runtime behaviourAll Java topics and weeks