Inheritance and Constructors
Introduction: 9.2.0
- Subclasses
inherit
public methods from the superclass they extend- They cannot access the private instance variables directly
- You still need to use the public accessor/mutator
- Subclasses do not inherit constructors from a superclass
- They cannot access the private instance variables directly
super()
- To initialize a superclass’s private variables, you need to call the superclass constructor
- use the keyword
super()
in the firest line of a subclass constructor - You pass in all the same parameters as you would calling the constructor normally
- use the keyword
- If a class has no constructor, the compiler will add a
no-argument
constructor - If a subclass never calls the superclass constructor, the compiler will automatically add a
super()
call- This will not work if the superclass doesn’t have a no-argument constructor!!
- Every parent class has it’s constructor called, down to the constructor for
java.lang.Object
- Every object eventually inherits from
Object
!
- Every object eventually inherits from
public class Animal {
private String species;
public Animal(String species) {
this.species = species;
}
// we need to explicitly include this one because we have a constructor above, so java won't create a no-argument constructor for us
public Animal() {
species = "Unknown";
/* The concept is outside of the scope of this course, but this constructor could have
* alternatively been written as:
*
* this("Unknown");
*
* This would call the first constructor (which takes in an argument), rather than
* rewriting everything from scratch. The strategy of "telescoping" constructors
* can be really convenient and prevent unneeded code reuse. */
}
}
public class Dog extends Animal {
private String breed;
public Dog(String breed) {
super("Canis Lupis Familiaris");
this.breed = breed;
}
}
public class Cat extends Animal {
private boolean likesWater;
public Cat() {
// because we don't include a superclass constructor, it will be called implicitly here!
likesWater = false;
}
}
Summary: 9.2.2
- Subclasses don’t have access to private instance variables from their superclass
- Constructors are not inherited
- The superclass constructor is called from the first line of the subclass constructor
- uses the keyword
super()
- Otherwise a no-argument constructor is called implicitly
- uses the keyword
- The actual parameters passed into the superclass constructor are used to initalize values in the superclass
- Superclass constructors are called for all parent classes
- Down to
java.lang.Object
- Down to
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.