Inheritance Flashcards
Inheritance
Enables a class to take on the properties and methods defined in another class. A subclass will inherit visible properties and methods from the superclass while adding members of its own.
Subclass
Is the derived class acquiring the properties and behaviors from another class.
Superclass
Is the base class whose members are being passed down.
Inheritance characteristics
Except for Object which is the starting ancestor of all classes in Java, ALL classes in Java have ONE and ONLY ONE direct superclass, which is called Single Inheritance. If a class does not have an explicit superclass, then it is implicitly a subclass of Object.
Inheritance principles
- A subclass inherits all visible (non-private) properties and behaviors (methods) from the superclass.
- A subclass DOES NOT inherit private properties or methods from the superclass.
- Constructors are NOT inherited.
- The subclass will then pass these traits through each subsequent generation if it becomes a superclass to its own subclasses.
- A Superclass can have multiple subclasses, however, a subclass may only have 1 superclass.
Object as a superclass
- In Java, all Objects are subclasses of the class java.lang.Object.
- An object is the only class in Java that does not have a superclass.
- The only things in the language that are not descendents of java.lang.Object are the primitives: long, int, double, boolean, etc.
- Even if no superclass is specified, all classes still implicitly extend from java.lang.Object, and inherit a set of common methods, such as:
.toString()
.equals()
.hashCode()
Casting to a superclass (upcasting)
Upcasting is widening, so it is implicit. ScientificCalculator sc = new ScientificCalculator(); Calculator c = sc; Object obj = c;
Casting to a subclass (downcasting)
Downcasting is narrowing, so must be explicit.
ScientificCalculator sc = new ScientificCalculator();
Calculator c = sc;
ScientificCalculator backToSc = (ScientificCalculator) c;