touque.ca > Education Commons > Java > Resources

Inheritance and …

instance methods

Instance methods can

  1. override methods of the superclass,
  2. be inherited from the superclass, or
  3. be brand new in the subclass.

instance fields

Instance fields can

  1. be inherited from the superclass or
  2. be brand new in the subclass.

Instance fields cannot override instance fields of the superclass, so an instance field should not have the same name as an instance field in the superclass. If it does, it will shadow the superclass field: you’ll have two fields with the same name, one in the superclass and one in the subclass. The main result of this will be confusion: you won’t be able to figure out why your class compiles but doesn’t properly execute!

constructors

“If a subclass constructor does not call the superclass constructor, the superclass is constructed with its default constructor. If the superclass does not have a default constructor, then the compiler reports an error” (Horstmann, 2002, p. 443).

Why the error? Because the compiler calls a constructor with no parameters (the default), and the call doesn’t match any of the existing constructors—they each have one or more parameters.

To ensure we never encounter this problem, our house style requires us to always call the appropriate superclass constructor explicitly.


Horstmann, C. (2002). Big Java. New York: John Wiley & Sons.

touque.ca > Education Commons > Java > Resources

[This page last updated 2020-12-23 at 12h13 Toronto local time.]