Inheritance and Interfaces, COMP SCI Ch. 9 and Ch. 10 – Study Notes
offline

Difficulty: Intermediate | Prerequisites: Chapters 7 and 8 (Arrays, ArrayLists, class design, accessors/mutators)


Big Picture

Inheritance and interfaces are Java's two main tools for building relationships between classes. Inheritance lets you create new classes by extending existing ones, reusing code and adding new behaviour. Interfaces define a contract that any class can promise to fulfil, enabling polymorphism, where the same method call does different things depending on the actual object. Together, these concepts are the backbone of object-oriented programming and show up heavily on exams.


TL;DR

Inheritance uses extends to let a subclass reuse and override methods from a superclass. Interfaces use implements to guarantee that a class provides certain methods. Polymorphism means the JVM picks the right version of a method at runtime based on the actual object type, not the declared reference type. Access modifiers (public, private, protected) control who can see what.


Key Terms

Inheritance

The mechanism of creating a new class (subclass) from an existing class (superclass), inheriting its methods and fields. Think of it as building on top of what already exists rather than starting from scratch.

Superclass (parent class)

The original class being extended. BankAccount is the superclass if SavingsAccount extends BankAccount.

Subclass (child class)

The class that extends the superclass. It inherits behaviour and state, and can add new methods or override existing ones.

extends keyword

The Java keyword that establishes an inheritance relationship: public class SavingsAccount extends BankAccount.

Override

Providing a new implementation of a method that already exists in the superclass. The overriding method must have the same name and parameter types (same signature).

super keyword

A reference to the parent class. super.methodName() calls the superclass version of a method. super() in a constructor calls the superclass constructor. You can only call super() once per constructor, and it must be the first statement.

instanceof operator

Tests whether an object is an instance of a particular class or interface. Used before casting to avoid runtime exceptions: if (obj instanceof BankAccount).

Casting (type cast)

Converting a reference from one type to another. Downcasting (superclass to subclass) is dangerous and should be guarded with instanceof: BankAccount a = (BankAccount) anObject;

Abstract method

A method declared without an implementation (no body). Written as a header only: abstract double getMeasure();

Abstract class

A class that cannot be instantiated directly. It may contain instance variables, constructors, concrete methods, and abstract methods. Subclasses must provide implementations for all abstract methods before they can be instantiated.

Interface

A type that specifies a set of abstract methods that implementing classes must define. Declared with the interface keyword. A class can implement multiple interfaces.

Polymorphism

The principle that the same method call can behave differently depending on the actual type of the object at runtime. Also called late binding or dynamic binding.

Late binding (dynamic binding)

The JVM determines which version of a method to call at runtime based on the actual object type, not the compile-time reference type.

Overloading (early binding)

Resolved at compile time using parameter matching. Different from overriding, which is resolved at runtime. Two methods with the same name but different parameter lists are overloaded.

Comparable interface

A built-in Java interface with a single method, compareTo(Object other), that returns a negative number, zero, or a positive number to indicate ordering.

Clone method

A method that creates a copy of an object. A shallow copy duplicates references (alias). A deep copy creates genuinely independent copies of all referenced objects.

Access modifiers

  • public: accessible by all classes everywhere.

  • private: accessible only within the class that declares it.

  • protected: accessible within the class, its subclasses, and other classes in the same package.

  • Package access (no modifier): accessible by all classes in the same package.


Core Content

Inheritance Basics

  • A subclass inherits all methods and instance variables from its superclass.

  • Methods in the superclass are not abstract (unlike interface methods); they have concrete implementations the subclass can use directly.

  • The primary advantage is code reuse: shared behaviour lives in the superclass, and subclasses add or modify only what differs.

  • Every class in Java extends Object either directly or indirectly. Object is the root superclass of all classes.

Three Things a Subclass Can Do

  • Override a method: supply a new implementation with the same signature as a superclass method. The subclass version replaces the inherited one.

  • Inherit a method: do nothing, and the superclass implementation applies to subclass objects automatically.

  • Add a method: define a new method that does not exist in the superclass. This method is available only on the subclass.

The super Keyword

  • super.methodName() calls the superclass version of an overridden method.

  • super() in a constructor invokes the superclass constructor.

  • You can only call super() once, and it must be the first line of the subclass constructor.

Casting and instanceof

  • Sometimes you need to convert a superclass reference to a subclass reference.

  • This is called downcasting: BankAccount a = (BankAccount) anObject;

  • If the cast is wrong, Java throws a ClassCastException at runtime.

  • Guard with instanceof first:

if (anObject instanceof BankAccount) {
    BankAccount a = (BankAccount) anObject;
}

Do Not Redeclare Instance Variables

  • A common mistake: declaring an instance variable in a subclass that already exists in the superclass. This creates a second, separate variable rather than reusing the inherited one. The inherited field becomes hidden, leading to subtle bugs.

Access Modifiers

  • public: any class can access it.

  • private: only the declaring class can access it. Subclasses cannot access private fields of their superclass directly (use accessor/mutator methods instead).

  • protected: the declaring class, its subclasses, and classes in the same package can access it. More open than private, less open than public.

  • Package access (default, no keyword): accessible by all classes in the same package. Nearly as open as public within the package, invisible outside it.

Clone Method

  • Shallow copy: copies references, so the original and clone share the same inner objects (alias).

  • Deep copy: creates independent copies of all inner objects.

  • Standard pattern:

public Object clone() {
    ShoppingCart x = new ShoppingCart();
    for (Item i : cart) {
        x.addItem(new Item(i.getName(), i.getPrice(), i.getQuantity()));
    }
    return x;
}
  • To use: BankAccount clonedAccount = (BankAccount) account.clone();

Abstract Classes

  • Declared with the abstract keyword: public abstract class ClassName

  • Cannot be instantiated directly. You cannot call new on an abstract class.

  • Can contain instance variables, constructors, concrete methods, and abstract methods.

  • A concrete subclass that extends the abstract class must implement all its abstract methods.


Interfaces

  • An interface declares abstract methods that implementing classes must define.

  • Syntax:

public interface Measurable {
    double getMeasure();
}
  • A class implements an interface with the implements keyword and must provide bodies for every method declared in the interface:

public class BankAccount implements Measurable {
    public double getMeasure() {
        return balance;
    }
}
  • A class can implement multiple interfaces, separated by commas.

Polymorphism

  • The reference type determines which methods you are allowed to call at compile time.

  • The actual object type determines which version of the method runs at runtime.

    • If x is declared as Measurable but holds a BankAccount, calling x.getMeasure() runs BankAccount's version.

    • If x holds a Country instead, it runs Country's version.

  • This is late binding (dynamic binding), resolved at runtime.

  • Overloading, by contrast, is early binding, resolved at compile time by matching parameter types.

The Comparable Interface

  • A built-in interface with one method: compareTo(Object otherObject)

  • Returns:

    • A negative number if the calling object should come before the argument.

    • Zero if they are equal.

    • A positive number if the calling object should come after the argument.

  • Used by many standard library methods (e.g. sorting).


Formulas / Key Syntax

Task

Syntax

Extend a class

public class Sub extends Super

Call superclass constructor

super(); (first line of constructor)

Call superclass method

super.methodName();

Implement an interface

public class X implements Y

Implement multiple interfaces

public class X implements Y, Z

Declare abstract class

public abstract class Name

Declare abstract method

abstract double getMeasure();

Test object type

if (obj instanceof ClassName)

Downcast

ClassName var = (ClassName) obj;

Comparable's method

a.compareTo(b)


Real-World Applications

Inheritance models real taxonomies: a Vehicle superclass with Car, Truck, and Motorcycle subclasses. Interfaces define capabilities across unrelated classes: Comparable lets both BankAccount and String be sorted, even though they share no superclass beyond Object. Polymorphism is why a single sort() method can handle any list of Comparable objects without knowing or caring what specific types are inside.


Common Misconceptions

  • Students confuse "implements" (for interfaces) with "extends" (for classes). A class extends one superclass and implements one or more interfaces.

  • Students think overriding and overloading are the same. Overriding replaces a superclass method with the same signature (dynamic binding, runtime). Overloading means multiple methods with the same name but different parameter lists (static binding, compile time).

  • Students redeclare instance variables in subclasses, thinking they are overriding them. This creates a hidden duplicate variable, not an override.

  • Students assume abstract classes cannot have constructors or concrete methods. They can; they simply cannot be instantiated directly.

  • Students believe that private members are inherited. Private fields do exist in the subclass object, but they are not directly accessible. The subclass must use public or protected accessors from the superclass to read or modify them.


Why It Matters / Exam Flags

⚠️ Be able to distinguish overriding from overloading. Expect exam questions that test whether a method call is resolved at compile time or runtime.

⚠️ Know that super() must be the first statement in a subclass constructor, and can only appear once.

⚠️ Understand the output of polymorphic method calls: given a reference type and an actual object type, which method version runs?

⚠️ Expect questions on access modifiers: what can a subclass access? What about classes in the same package?

⚠️ Know that Comparable has a single method (compareTo) and what its return values mean.

⚠️ Abstract class questions: can you instantiate one? (No.) Can it have concrete methods? (Yes.) What must a subclass do? (Implement all abstract methods.)


Quick Self-Test

True or False: A class can extend multiple superclasses in Java.

False. Java supports single inheritance only. A class extends one superclass (and implements multiple interfaces).

Fill in the blank: The process by which the JVM determines which version of a method to call at runtime is called _______.

Late binding (or dynamic binding).

True or False: An abstract class can contain instance variables and constructors.

True.

Fill in the blank: a.compareTo(b) returns a negative number when a is _______ b.

Less than (i.e., should come before)

True or False: Overloading is resolved at runtime.

False. Overloading is resolved at compile time (early binding). Overriding is resolved at runtime.


Practice Q&A

Q: What is the difference between inheriting from a class and implementing an interface?

A: Inheriting from a class (extends) gives the subclass concrete method implementations and instance fields to reuse. Implementing an interface (implements) requires the class to provide its own implementations for the interface's abstract methods. A class can extend only one superclass but implement many interfaces.

Q: What does the instanceof operator do, and when should you use it?

A: It tests whether an object is an instance of a given class or interface. Use it before downcasting to avoid a ClassCastException.

Q: Explain the difference between a shallow copy and a deep copy.

A: A shallow copy duplicates the top-level object but shares references to the inner objects (they are aliases). A deep copy creates entirely new copies of all inner objects so the original and clone are fully independent.

Q: Can you instantiate an abstract class? What must happen before objects of that type exist?

A: No, you cannot instantiate an abstract class directly. A concrete subclass must extend it and implement all its abstract methods; then you instantiate the subclass.

Q: If a subclass does not override a superclass method, what happens when that method is called on a subclass object?

A: The superclass version of the method runs. The subclass inherits it as-is.

Q: What does protected access mean in Java?

A: The member is accessible within the declaring class, its subclasses (even in different packages), and all other classes in the same package.


Connections to Other Topics

Inheritance and interfaces build directly on the class-design principles from Chapter 8 (cohesion, coupling, accessors/mutators). The Comparable interface relies on the array and ArrayList knowledge from Unit 7, since sorting and searching collections require a defined ordering. These concepts also lay the groundwork for more advanced patterns like the Strategy pattern and Dependency Injection, which are common in software engineering courses.


Related Terms / Search Tags

inheritance, extends, subclass, superclass, parent class, child class, method overriding, override, method overloading, overload, super keyword, super(), constructor chaining, interface, implements, abstract method, abstract class, polymorphism, late binding, dynamic binding, early binding, static binding, Comparable, compareTo, instanceof, downcasting, type casting, access modifier, public, private, protected, package access, clone, shallow copy, deep copy, immutable, Object class, code reuse, COMP SCI, Texas A&M, intro to programming, Chapter 9, Chapter 10