Chapter 4.3: Inheritance

Object Oriented Programming with Java
Superclass and subclassextendssuper and constructor chainingOverriding and @Override protectedfinalis-a and has-aInheritance or composition?Multiple inheritanceThe Object classtoString, equals, hashCode
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Concept

Define inheritance, superclass and subclass; recognize the “is-a” relationship.

Syntax

Write a subclass with extends; explain what is inherited and what is not.

Constructors

Use super(...) and super.method(); trace the order of the constructor chain.

Overriding

Override a method, tell overriding from overloading, and use @Override.

Access and restriction

Explain protected access and how final restricts inheritance.

The Object class

Write toString, equals and hashCode correctly; know the difference between == and equals.

The Idea of Inheritance

What Is Inheritance?

  • Inheritance: building a new class from an existing one by taking over its fields and methods and adding new or modified behavior.
  • The existing class: the superclass.
  • The new class: the subclass.
  • A subclass can add fields and methods; inherited fields are not redeclared.
Analogy: “Every rectangle is a shape.” A rectangle has everything a shape has, plus its own width, height and area().
superclassShape- color : String+ draw() : voidextendsRectangle- width : double- height : double+ area() : doublesubclass

The Idea of Inheritance

Subclassing with extends

// base class (superclass)
public class Shape {
    // fields and methods of the base class
    // ...
}

// new class (subclass), derived from Shape
public class Rectangle extends Shape {
    // fields and methods of the new class
    // ...
}
  • Syntax: class Sub extends Super. extends means “builds on”.
  • extends names exactly one class.
  • The subclass uses the superclass’s public and protected members as if they were its own.
  • Redeclaring a superclass field with the same name in the subclass hides it: you get two separate variables and a lot of confusion. Don’t do it.
  • A class without extends implicitly extends Object.
RectanglesubclassShapesuperclassObjectimplicit superclassextendsextends

The Idea of Inheritance

Subclass and Superclass

  • A subclass behaves like its superclass and adds behavior of its own.
  • This is why inheritance is also called specialization: the subclass represents a more specific group.
  • Every cat is an animal, but not every animal is a cat.
  • The Java class hierarchy starts with the Object class in package java.lang.
  • Every class inherits from Object, directly or indirectly.
ObjectAnimalStringShapeCatDogRectangleup: general · down: specific

The Idea of Inheritance

Kinds of Inheritance

  • Single: one subclass, one superclass. Cat extends Animal.
  • Multilevel: a chain. Cat gets the members of LivingThing through Animal; each level carries everything of the one above.
  • Hierarchical: many subclasses of one superclass. Common code is written once; each subclass adds only its differences.
  • Multiple: a class with several superclasses. Java does not allow this for classes; interfaces cover the same need.
In Java the class hierarchy is a tree: its root is Object, and every class except Object has exactly one direct superclass. Chains can be arbitrarily deep, but deep chains are hard to read and change.
SingleMultilevelHierarchicalMultiple (not for classes)AnimalCatLivingThingAnimalCatAnimalCatDogBirdBCD✗done with interfaces

The Idea of Inheritance

What Is Inherited?

MemberInherited by the subclass?Note
public / protected fields and methodsYesUsed directly in the subclass.
Members with no modifier (package access)Only within the same packageA subclass in another package cannot access them.
private fieldsPresent in the object, but not directly accessibleUsed through the superclass’s public/protected methods (getters, setters).
private methodsNoInvisible; cannot be overridden.
ConstructorsNoNot inherited; the subclass constructor calls them with super(...).
static membersAccessibleBelong to the class; not overridden, only hidden.

In short: a subclass object contains all the superclass fields; the access modifier decides which ones it can reach directly.

The Idea of Inheritance

Inside a Subclass Object

  • new Cat(...) creates one object; there is no separate object for the superclass.
  • The object also has room for the fields inherited from the superclass. They are there even when private; only Cat’s code cannot name them.
  • super is not a separate object: it is a way to reach the superclass part of the same object through the superclass’s code.
Stackmain()kHeap: one objectCat objectObject partAnimal part- name = "Mavi"- health = 100.0Cat part- indoor = truethis and super are the same object

Proof: getClass() in the constructor

class Animal {
    Animal() {
        System.out.println("In Animal(): "
            + getClass().getSimpleName());
    }
}
class Cat extends Animal { }
// in main:
new Cat();
new Animal();
In Animal(): Cat
In Animal(): Animal

Even while the Animal constructor runs, the object’s real class is Cat: the constructor chain builds the parts of the same object in turn.

The Idea of Inheritance

Moving Common Code Up

Generalization: finding fields and methods repeated in several classes and moving them into a common superclass. It is the reverse of specialization.

Before: the same code in two places

class Student {
    private String name;
    private int age;
    private double gpa;
    String info() { return name + " (" + age + ")"; }
}
class Teacher {
    private String name;
    private int age;
    private String subject;
    String info() { return name + " (" + age + ")"; }
}

If the age format changes, both classes must be fixed; forget one and the output is inconsistent.

After: the common part lives in Person

class Person {
    private String name;
    private int age;
    Person(String n, int a) { name = n; age = a; }
    String info() { return name + " (" + age + ")"; }
}
class Student extends Person {
    private double gpa;
    Student(String name, int age, double gpa) {
        super(name, age);
        this.gpa = gpa;
    }
    @Override String info() {
        return super.info() + ", gpa " + gpa;
    }
}   // Teacher likewise: adds subject
Ece (20), gpa 3.4
Murat (41), Physics

Ask before moving: “Is every student a person?” If yes, generalization is right; if the two classes merely share a few fields, composition fits better.

Animal Example

The Animal Class Hierarchy

Animal- name : String- age : int- health : double+ getName() : String+ speak() : void+ eat(double) : void+ sleep() : void+ toString() : StringCat+ speak() : void+ hunt() : voidDog+ speak() : void+ playBall() : voidBird+ speak() : void+ fly() : voidHorse+ speak() : void+ run() : void

Common fields and methods are written once, in Animal. Each subclass overrides speak() in its own way and adds a method of its own. In UML, inheritance is drawn as an arrow with a hollow triangle pointing to the superclass.

Animal Example

The Animal and Dog Classes

public class Animal {
    private String name;     // common fields
    private int age;
    private double health;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
        this.health = 100.0;
    }
    public String getName() { return name; }   // access to private name
    public void speak() {
        System.out.println("This animal speaks.");
    }
    public void sleep() {
        health += 5;
        System.out.println(name + " slept. Health: " + health);
    }
}

Superclass Animal: the fields and behavior shared by all animals.

public class Dog extends Animal {
    public Dog(String name, int age) {
        super(name, age);   // superclass sets the fields
    }
    @Override
    public void speak() {   // changes inherited behavior
        System.out.println(getName() + " barks.");
    }
    public void playBall() { // behavior only Dog has
        System.out.println(getName() + " is playing ball!");
    }
}
Dog dog = new Dog("Karabaş", 4);
dog.speak();     // Dog's version
dog.playBall();   // Dog only
dog.sleep();       // inherited
Karabaş barks.
Karabaş is playing ball!
Karabaş slept. Health: 105.0

The subclass Dog writes only the difference; sleep() works without being written at all.

Animal Example

Benefits of Inheritance

Reuse

Superclass methods and fields are used in the subclass without being rewritten.

Extension

An existing class gains new features without changing its code.

Modification

Superclass methods can be changed in the subclass by overriding them.

Calculator- memory : double+ add(int, int) : double+ multiply(int, int) : double+ showMemory() : doubleAdvancedCalculator+ pow(double, int) : double+ factorial(int) : long
public class AdvancedCalculator
        extends Calculator {
    // new ability: exponentiation
    public double pow(double base, int pow) {
        double result = 1.0;
        for (int i = 0; i < pow; i++) {
            result *= base;
        }
        return result;
    }
    // factorial(int) is added likewise
}
// in main
AdvancedCalculator h = new AdvancedCalculator();
System.out.println(h.add(5, 3));         // 8.0  (inherited)
System.out.println(h.showMemory()); // 8.0  (inherited)
System.out.println(h.pow(2, 5));            // 32.0 (new)

Constructors and super

The super Keyword

  • super(...): called inside a subclass constructor, it runs the superclass constructor, which initializes the superclass fields.
  • super(...) must be the first statement of the constructor (before Java 25; Java 25 allows statements that do not touch the object before it).
  • If omitted, the compiler silently inserts super(); (no arguments).
  • super.method(): reaches a superclass method with a dot; used to call the superclass version from inside an overriding method.
  • Principle: each class manages only its own data. Cat does not assign Animal’s name field itself; it leaves that to super(name).
class Cat extends Animal {
    private boolean indoor;

    Cat(String name, boolean indoor) {
        super(name);         // Animal(String)
        this.indoor = indoor;  // its own data
    }

    @Override
    public String toString() {
        return super.toString()   // Animal's
               + ", Indoor: " + indoor;
    }
}
// in main
System.out.println(new Cat("Mavi", true));

Output

Name: Mavi, Health: 100.0, Indoor: true

Animal’s toString() returns the name and health; Cat appends only its own field.

Constructors and super · Step-by-step code trace

The super.introduce() Chain: Code Trace

LivingThingintroduce()Animalintroduce()Catintroduce()Call stackCat.introduce()main()obj: Cat #1lookup starts at the real class: Cat.introduce()

The object is a Cat; lookup starts at the bottom and finds Cat.introduce().

LivingThingintroduce()Animalintroduce()Catintroduce()superCall stackAnimal.introduce()Cat.introduce()main()obj: Cat #1

super.introduce() calls the version one level up. Cat.introduce waits on the stack.

LivingThingintroduce()Animalintroduce()Catintroduce()supersuperCall stackLivingThing.introduce()Animal.introduce()Cat.introduce()main()obj: Cat #1

The object is still a Cat, yet super inside Animal always means LivingThing: no dynamic binding.

LivingThingintroduce()Animalintroduce()Catintroduce()Call stackLivingThing.introduce()Animal.introduce()Cat.introduce()main()obj: Cat #1I'm alive printed, LivingThing.introduce() returns

The topmost version runs and prints the first line, then returns.

LivingThingintroduce()Animalintroduce()Catintroduce()Call stackAnimal.introduce()Cat.introduce()main()obj: Cat #1

Animal.introduce() resumes where it left off: I'm an animal.

LivingThingintroduce()Animalintroduce()Catintroduce()Call stackCat.introduce()main()obj: Cat #1

Finally Cat.introduce() prints its own line.

LivingThingintroduce()Animalintroduce()Catintroduce()Call stackmain()obj: Cat #1calls bottom-up, output top-down

The calls went Cat → Animal → LivingThing and the output came back in reverse: each class first had its superclass do its work, then added its own difference.

class LivingThing {
    void introduce() { System.out.println("I'm alive"); }
}
class Animal extends LivingThing {
    void introduce() {
        super.introduce();
        System.out.println("I'm an animal");
    }
}
class Cat extends Animal {
    void introduce() {
        super.introduce();
        System.out.println("I'm a cat");
    }
}
new Cat().introduce();   // main

Constructors and super · Step-by-step code trace

Constructor Chain: new Cat("Mavi", true)

cat—Cat objectfrom AnimalCat's ownname = nullhealth = 0.0indoor = false

new: memory for the object is allocated first; all fields (Animal’s included) get default values.

cat—Cat objectfrom AnimalCat's ownname = nullhealth = 0.0indoor = false

The Cat constructor is called. Before it does its own work, the superclass part must be ready.

cat—Cat objectfrom AnimalCat's ownname = nullhealth = 0.0indoor = false

super(name): the Animal constructor is called; the Cat constructor waits.

cat—Cat objectfrom AnimalCat's ownname = nullhealth = 0.0indoor = false

Animal first calls its own superclass: Object(). Every chain ends at Object.

cat—Cat objectfrom AnimalCat's ownname = "Mavi"health = 0.0indoor = false

Object() returns. Animal fills its own field: name = "Mavi".

cat—Cat objectfrom AnimalCat's ownname = "Mavi"health = 100.0indoor = false

health = 100.0.

cat—Cat objectfrom AnimalCat's ownname = "Mavi"health = 100.0indoor = false

The Animal constructor prints its message and returns: the superclass printed first.

cat—Cat objectfrom AnimalCat's ownname = "Mavi"health = 100.0indoor = true

The Cat constructor resumes: indoor = true.

cat—Cat objectfrom AnimalCat's ownname = "Mavi"health = 100.0indoor = true

The Cat constructor prints its message.

catCat objectfrom AnimalCat's ownname = "Mavi"health = 100.0indoor = true

The constructor is done; the object’s address is stored in cat.

catCat objectfrom AnimalCat's ownname = "Mavi"health = 100.0indoor = true

Constructors finish top-down: Object → Animal → Cat.

class Animal {
    private String name;
    private double health;
    Animal(String name) {
        super();   // calls Object()
        this.name = name;
        health = 100.0;
        System.out.println("Animal constructor");
    }
}
class Cat extends Animal {
    private boolean indoor;
    Cat(String name, boolean indoor) {
        super(name);
        this.indoor = indoor;
        System.out.println("Cat constructor");
    }
}
// in main
Cat cat = new Cat("Mavi", true);
System.out.println("Object ready");

Constructors and super

Implicit super() and Errors

1) The superclass has no no-arg constructor

class Animal {
    private String name;
    Animal(String name) { this.name = name; }
}
class Cat extends Animal {
    Cat(String name) {
        // the compiler inserts super(); here
        System.out.println("Cat");
    }
}
error: constructor Animal in class Animal
  cannot be applied to given types;
  required: String
  found:    no arguments

2) super(...) is not the first statement

Cat(String name) {
    System.out.println("Cat");
    super(name);
}
error: call to super must be first
  statement in constructor
Fix: call the right superclass constructor explicitly on the first line of the subclass constructor: super(name);

For a class with no constructors, the compiler adds a no-arg default constructor; as soon as you write one, it does not.

Cat(String name)no super(…) writtensuper();added by compilerAnimal() ?missing: only Animal(String)fix: super(name); on line one

Constructors and super · Step-by-step code trace

this(...) and super(...): Code Trace

StackHeapManager(name)main()y?Manager #1namenullsalary0.0bonus0.0Employee part: name, salarynew: object allocated, fields default

new first allocates the object; all three fields hold default values. Then Manager(String) is called.

StackHeapManager(name,bonus)Manager(name)main()y?Manager #1namenullsalary0.0bonus0.0Employee part: name, salarythis(...) → another constructor of the same class

The first line, this(name, 5000.0), passes control to the two-argument constructor of the same class. Manager(String) waits before running its body.

StackHeapEmployee(name)Manager(name,bonus)Manager(name)main()y?Manager #1namenullsalary0.0bonus0.0Employee part: name, salarysuper(name) → superclass constructor

super(name): the one-argument constructor of the superclass Employee. Building the Manager part waits until the Employee part is done.

StackHeapEmployee(name,salary)Employee(name)Manager(name,bonus)Manager(name)main()y?Manager #1namenullsalary0.0bonus0.0Employee part: name, salarythis(...) again; the chain ends in implicit super()

Employee also delegates with this(...). That constructor’s first line is neither this nor super, so the compiler inserts an implicit super(): Object() runs and returns.

StackHeapEmployee(name,salary)Employee(name)Manager(name,bonus)Manager(name)main()y?Manager #1name"Ayşe"salary20000.0bonus0.0Employee part: name, salaryEmployee part built

The first body runs here: name and salary are set and the first line is printed. The calls went bottom-up; the bodies complete starting from the topmost class.

StackHeapEmployee(name)Manager(name,bonus)Manager(name)main()y?Manager #1name"Ayşe"salary20000.0bonus0.0Employee part: name, salaryEmployee(String) resumes

The two-argument constructor returned; Employee(String) prints its line.

StackHeapManager(name,bonus)Manager(name)main()y?Manager #1name"Ayşe"salary20000.0bonus5000.0Employee part: name, salarybuilding the Manager part

super(name) is done. Only now does the subclass set its own field: bonus = 5000.0.

StackHeapManager(name)main()y?Manager #1name"Ayşe"salary20000.0bonus5000.0Employee part: name, salaryfirst constructor called finishes last

Finally the first one called, Manager(String), finishes. Four constructors ran, but only one object was built.

StackHeapmain()yManager #1name"Ayşe"salary20000.0bonus5000.0Employee part: name, salaryincome() = 20000.0 + 5000.0

The object’s address is stored in y. income() adds the inherited getSalary() to its own bonus: 25000.0.

class Employee {
    private String name;  private double salary;
    Employee(String name) {
        this(name, 20000.0);
        System.out.println("Employee(String)");
    }
    Employee(String name, double salary) {
        this.name = name;  this.salary = salary;
        System.out.println("Employee(String, double)");
    }
    double getSalary() { return salary; }
}
class Manager extends Employee {
    private double bonus;
    Manager(String name) {
        this(name, 5000.0);
        System.out.println("Manager(String)");
    }
    Manager(String name, double bonus) {
        super(name);
        this.bonus = bonus;
        System.out.println("Manager(String, double)");
    }
    double income() { return getSalary() + bonus; }
}
Manager y = new Manager("Ayşe");   // main
System.out.println(y.income());

Constructors and super · Step-by-step code trace

Initialization Order with Inheritance: Code Trace

Classes (once)Parentstatic:runningChildstatic:waitingObjects1. Parent static2. Child static3. Parent fields4. Parent()5. Child fields6. Child()loading Parent: superclass first

For the first new Child(), the JVM must initialize class Child. The superclass goes first: Parent’s static block runs.

Classes (once)Parentstatic:done ✓Childstatic:runningObjects1. Parent static2. Child static3. Parent fields4. Parent()5. Child fields6. Child()loading Child

Then Child’s static block. Class initialization happens once per program run.

Classes (once)Parentstatic:done ✓Childstatic:done ✓ObjectsChild #1a1b0(a: Parent, b: Child)1. Parent static2. Child static3. Parent fields4. Parent()5. Child fields6. Child()Child() → implicit super() → Parent fields

The object is allocated (a and b are 0). Child() first calls an implicit super(); Parent’s field initializers run before the Parent() body: a = value(...).

Classes (once)Parentstatic:done ✓Childstatic:done ✓ObjectsChild #1a1b0(a: Parent, b: Child)1. Parent static2. Child static3. Parent fields4. Parent()5. Child fields6. Child()Parent() body

Then the Parent() body. At this point b is still 0: the Child part has not been initialized at all.

Classes (once)Parentstatic:done ✓Childstatic:done ✓ObjectsChild #1a1b1(a: Parent, b: Child)1. Parent static2. Child static3. Parent fields4. Parent()5. Child fields6. Child()super() returned → Child fields

After super() returns, the subclass field initializers run: b = value("Child field").

Classes (once)Parentstatic:done ✓Childstatic:done ✓ObjectsChild #1a1b1(a: Parent, b: Child)1. Parent static2. Child static3. Parent fields4. Parent()5. Child fields6. Child()Child() body: object ready

Last comes the Child() body. Order: superclass fields → superclass constructor → subclass fields → subclass constructor.

Classes (once)Parentstatic:done ✓Childstatic:done ✓ObjectsChild #1a1b1(a: Parent, b: Child)Child #2a1b1(a: Parent, b: Child)1. Parent static2. Child static3. Parent fields4. Parent()5. Child fields6. Child()second object: no static blocks

Second new Child(): the classes are already initialized, so the static blocks do not run again. The four per-object steps repeat in the same order.

class Parent {
    static { System.out.println("Parent static"); }
    int a = value("Parent field");
    Parent() { System.out.print("Parent(), "); }
    static int value(String s) {
        System.out.print(s + ", ");
        return 1;
    }
}
class Child extends Parent {
    static { System.out.println("Child static"); }
    int b = value("Child field");
    Child() { System.out.println("Child()"); }
}
// in main:
new Child();
new Child();

Overriding

Overriding a Method

Overriding: a subclass rewrites an inherited method with the same signature to give it its own behavior.

  • Name and parameter list must be identical.
  • The return type must be the same (or a subtype).
  • Access cannot be narrowed: a public method stays public.
  • final, static and private methods cannot be overridden.
class Shape {
    public void draw() {
        System.out.println("Drawing a shape.");
    }
}
class Rectangle extends Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle.");
    }
}
// in main
new Shape().draw();
new Rectangle().draw();
Drawing a shape.
Drawing a rectangle.
// in subclass: void draw()
error: draw() in Rectangle cannot override
  draw() in Shape
  attempting to assign weaker access
  privileges; was public
// in subclass: public int draw()
error: draw() in Rectangle cannot override
  draw() in Shape
  return type int is not compatible
  with void

Overriding

Overriding vs. Overloading

OverridingOverloading
Where?In a subclass, for an inherited methodIn the same class (or a subclass)
NameSameSame
ParametersSameDifferent (number or type)
Return typeSame or a subtypeAny
PurposeChange inherited behaviorDo the same job with different inputs
Resolved atRun time (actual type of the object)Compile time (argument types)
class Rectangle extends Shape {
    @Override
    public void draw() { ... }             // overriding
    public void draw(String color) { ... }  // overloading
}

Output of d.draw("Mavi")

Drawing a blue rectangle.

Both ideas underlie polymorphism.

Overriding

The @Override Annotation

  • @Override is an annotation: it states that the method overrides an inherited method.
  • It tells the compiler to check this: if the superclass has no such method, compilation fails.
  • It makes the code easier to read; other developers see at once that the method comes from the superclass.
  • It is optional, but you should always write it: it catches typos immediately.
public class Rectangle extends Shape {
    // override the inherited method
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle.");
    }
}

Typo: Draw (capital D)

    @Override
    public void Draw() { ... }
error: method does not override or implement
  a method from a supertype

Without @Override, Draw() would silently become a new method, and calls to draw() would still run Shape’s version.

Overriding

Overriding Rules in Detail

AspectAllowed in the subclassjavac if broken
Name and parametersExactly the sameNo error: a new method (overload)
Return typeSame or a subtype (covariant)return type String is not compatible with Animal
AccessSame or wider: protected → publicattempting to assign weaker access privileges
Checked exceptionsSame, more specific, or noneoverridden method does not throw Exception
staticCannot switch between instance and staticoverriding method is static / overridden method is static
final methodCannot be overriddenoverridden method is final
private methodInvisible; a same-named method is unrelatedNo error (error with @Override)
The common reason: a subclass object must work wherever a superclass object is expected. The superclass’s promise (what it returns, who can call it, which exceptions it may throw) can be kept or widened, never narrowed.

Overriding

Covariant Return Types

class Animal {
    Animal reproduce() { return new Animal(); }
    public String toString() { return "Animal"; }
}
class Cat extends Animal {
    @Override
    Cat reproduce() { return new Cat(); }  // subtype
    void meow() { System.out.println("meow"); }
    public String toString() { return "Cat"; }
}
// in main:
Cat k = new Cat();
k.reproduce().meow();   // no cast needed
Animal h = k;
System.out.println(h.reproduce());
meow
Cat
  • An overriding method may return a subtype of the superclass method’s return type: a covariant return type.
  • A caller holding a Cat reference gets a Cat directly; no (Cat) cast is needed.
  • A caller holding an Animal reference loses nothing: a Cat is also an Animal.
  • This works only for reference types; you cannot return long instead of int.

Unrelated type: String reproduce()

error: reproduce() in Cat cannot override
  reproduce() in Animal
  return type String is not compatible with Animal

Overriding

private Methods Are Not Overridden

class Parent {
    private void greet() { System.out.println("Parent.greet"); }
    void call() { greet(); }
}
class Child extends Parent {
    void greet() { System.out.println("Child.greet"); } // new
}
// in main:
Child a = new Child();
a.call();
a.greet();
Parent.greet
Child.greet

If @Override is added to the method in Child

error: method does not override or implement
  a method from a supertype
  • A private method is invisible to subclasses; a same-named subclass method is an unrelated new one.
  • In Parent.call(), greet() is bound at compile time to Parent’s private method, so Parent.greet is printed even for a Child.
  • Using @Override catches this at compile time.
Likewise for static methods: a subclass static method with the same signature does not override the parent’s, it only hides it.

Overriding

Example: A Product Hierarchy

class Product {
    private String name;
    private double price;
    Product(String name, double price) {
        this.name = name; this.price = price;
    }
    double taxRate() { return 0.20; }
    double salePrice() { return price * (1 + taxRate()); }
    @Override public String toString() {
        double f = Math.round(salePrice() * 100) / 100.0;
        return name + ": " + f + " TL";
    }
}
class Food extends Product {
    Food(String name, double price) { super(name, price); }
    @Override double taxRate() { return 0.01; }
}
class SaleProduct extends Product {
    private double discount;
    SaleProduct(String name, double price, double discount) {
        super(name, price);
        this.discount = discount;
    }
    @Override double salePrice() {
        return super.salePrice() * (1 - discount);
    }
    @Override public String toString() {
        return super.toString()
            + " (" + (int) (discount * 100) + "% off)";
    }
}
Product[] cart = {new Product("Pen", 50),
    new Food("Bread", 10),
    new SaleProduct("Headphones", 1000, 0.25)};
for (Product u : cart) System.out.println(u);
Pen: 60.0 TL
Bread: 10.1 TL
Headphones: 900.0 TL (25% off)
  • Food changes only taxRate(); salePrice() and toString() are not written there, yet they use 1%, because the call inside Product is chosen by the object’s class.
  • SaleProduct does not replace the superclass computation, it extends it: it applies the discount to super.salePrice(). 1000 × 1.20 × 0.75 = 900.

Access and Restriction

The protected Access Level

ModifierSame classSame packageSubclass
(other package)
Everywhere
private✓✗✗✗
(none: package)✓✓✗✗
protected✓✓✓✗
public✓✓✓✓
  • public: the members are accessible from everywhere. private: only from inside the class.
  • protected sits between the two: the class itself, its subclasses and other classes in the same package can access it.
  • A subclass can reach the private fields of its superclass only through inherited public or protected methods.

Good practice: keep fields private; expose the operations subclasses need as protected methods.

Access and Restriction

protected: Code Example

package animals;

public class Animal {
    protected String name;  // subclasses
    private double health;  // Animal only

    public Animal(String name) {
        this.name = name;
        health = 100.0;
    }
    public double getHealth() { return health; }
    protected void heal(double amount) {
        health += amount;
    }
}
package indoor;     // another package
import animals.Animal;

public class Cat extends Animal {
    public Cat(String name) { super(name); }
    public void sleep() {
        // protected field: allowed
        System.out.println(name + " sleeps.");
        // health += 5;  // private: error
        heal(5);   // protected method
        System.out.println("Health: "
                           + getHealth());
    }
}

Output of new Cat("Mavi").sleep();

Mavi sleeps.
Health: 105.0

If the comment is removed

error: health has private access in Animal

Access and Restriction

A Subtle protected Rule

package animals;
public class Animal {
    protected String name;
    public Animal(String name) {
        this.name = name;
    }
}
package indoor;
import animals.Animal;
public class Cat extends Animal {
    public Cat(String name) { super(name); }
    void compare(Cat k, Animal h) {
        System.out.println(name);    // own field
        System.out.println(k.name);  // via Cat
        System.out.println(h.name);  // via Animal
    }
}
indoor/Cat.java:8: error: name has protected access in Animal
        System.out.println(h.name);
  • A subclass in another package can reach a protected member only through a reference of its own type (or its subtypes): name and k.name are fine.
  • h, however, may point to any Animal, a Dog for example. Cat is not allowed to touch the internals of another subclass.
  • Classes in the same package have no such restriction: there, protected includes package access.

Access and Restriction

Restricting Inheritance with final

  • The final keyword can be used to restrict inheritance.
  • A final method cannot be overridden in any subclass.
  • No class can extend a final class. Examples: String, Math, Integer.
class Animal {
    public final void breathe() { ... }
}
class Cat extends Animal {
    public void breathe() { ... }
}
error: breathe() in Cat cannot override
  breathe() in Animal
  overridden method is final
final class Fixed { ... }
class Test extends Fixed { }
error: cannot inherit from final Fixed
Why? Security and consistency: String must stay immutable, and no subclass should be able to break that promise.

On variables, final means something else: the value is assigned once (a constant).

class Testfinal class Fixedextends ✗Cat.breathe()final breathe()override ✗

Access and Restriction

Restricting an Object’s View

  • An object can be assigned to a variable of a superclass type (upcasting): every Tire is a Part.
  • Only the methods of the superclass are then exposed.
  • Whatever the object’s real class, the variable’s type decides what we can call.
Part pTire objectPart portion · visible via pbrand = "Petlas"serialNo = "XYZ-123"serialNumber()Tire portion · hidden from psize = "225/45R17"winter = trueisWinter()
Part p = new Tire("Petlas", "XYZ-123", "225/45R17", true);
System.out.println(p.serialNumber());   // allowed → XYZ-123
// p.isWinter()                         // not allowed
error: cannot find symbol
  symbol:   method isWinter()
  location: variable p of type Part

To reach a Tire-only method you need a type check (instanceof) followed by a downcast.

Relationships Between Classes

is-a and has-a Relationships

Is-a (inheritance)

  • One class is derived from another; the subclass is a kind of the superclass.
  • A subclass object can also be used as a superclass object.

Has-a (composition)

  • A class has a field whose type is another class.
  • The object holds references to other objects.
Vehicle# speed : int+ accelerate(int) : voidCar- engine : Engine+ drive() : voidEngine- horsepower : int+ start() : voidis-ahas-a
// is-a relationship (inheritance)
public class Car extends Vehicle {
    // has-a relationship (composition)
    private Engine engine;

    public Car(int horsepower) {
        engine = new Engine(horsepower);
    }
    public void drive() {
        engine.start();   // delegate
        accelerate(50);         // inherited
        System.out.println("Speed: " + speed
                           + " km/h");
    }
}
// Engine: field horsepower and start():
//   "Engine started: " + horsepower + " hp"

new Car(110).drive();

Engine started: 110 hp
Speed: 50 km/h

Relationships Between Classes · Step-by-step code trace

is-a and has-a: Code Trace

StackHeapCar()thishp90main()Car #1speed (Vehicle)0enginenullVehicle part (speed) + Car part (engine)

new Car(90): one object, holding speed from the superclass Vehicle and its own engine field (is-a).

StackHeapCar()thishp90main()Car #1speed (Vehicle)0engineEngine #2hp90

The constructor creates a second object: a car is not an engine, it has one (has-a). The link is a reference.

StackHeapdrive()thismain()Car #1speed (Vehicle)0engineEngine #2hp90

drive() runs on the Car object.

StackHeapstart()thisdrive()thismain()Car #1speed (Vehicle)0engineEngine #2hp90engine.start() → the Engine object does the work

engine.start(): Car does not do the work itself; it follows the reference and delegates to the Engine object.

StackHeapdrive()thismain()Car #1speed (Vehicle)50engineEngine #2hp90accelerate(50): method inherited from Vehicle

accelerate(50) is not written in Car; it is inherited from Vehicle and sets the same object’s speed to 50.

StackHeapdrive()thismain()Car #1speed (Vehicle)50engineEngine #2hp90

Inheritance (speed, accelerate) and composition (engine) worked together in one class.

class Engine {
    private int hp;
    Engine(int hp) { this.hp = hp; }
    void start() {
        System.out.println("Engine: " + hp + " hp");
    }
}
class Car extends Vehicle {        // is-a
    private Engine engine;           // has-a
    Car(int hp) { engine = new Engine(hp); }
    void drive() {
        engine.start();  accelerate(50);
        System.out.println("Speed: " + speed);
    }
}
new Car(90).drive();   // main

Relationships Between Classes

Multiple Inheritance

  • Java does not support multiple inheritance of classes: a class extends exactly one class.
  • The diamond problem: if B and C override print() differently, which one does D get?
  • When you need features of several classes: use composition and interfaces (a class can implement many interfaces).
A+ print()B+ print()C+ print()Dprint() → ?
class D extends B, C { }   // invalid
error: '{' expected
interface Chargeable { void charge(); }
class ElectricCar extends Car
                      implements Chargeable {
    @Override
    public void charge() {
        System.out.println("Charging.");
    }
}

Relationships Between Classes

Design Principles for Inheritance

The “is-a” test

If “every X is a Y” is false, do not use inheritance. A Car is not an Engine; it has one → composition.

Each class manages its own data

Superclass fields get their values through super(...) and superclass methods; fields stay private.

Override the general methods

Every meaningful class should override toString and equals (and, with it, hashCode).

Common concepts go into abstract classes

Concepts shared by subclasses should be modeled with abstract classes, if “Animal” on its own should never be an object.

Relationships Between Classes

Inheritance or Composition?

Inheritance (extends)Composition (object as a field)
Relationshipis-a: “every X is a Y”has-a: “an X has a Y”
CouplingTight: the subclass depends on the superclass’s implementation tooLoose: depends only on the inner object’s public methods
ReuseAutomatic: every public method comes along (wanted or not)Selective: you write only the methods you want to forward
ChangeThe superclass is fixed at compile timeThe field can be swapped for another object at run time
Use in place of the supertypeDirectly: Animal h = new Cat()If both implement a common interface
Use inheritance

when the is-a relationship truly holds and the superclass was designed and documented for extension: Cat – Animal.

Use composition

when you only want to reuse another class’s code: a Stack is not an ArrayList; it keeps a list inside and offers only add/remove.

Relationships Between Classes · Step-by-step code trace

Fragile Base Class: Code Trace

StackHeapmain()lCountingList #1addCount0size0items[ ]size, items: MyList part (private)adding three items: expected count 3

CountingList extends MyList to count the items added. Both add methods are overridden.

StackHeapCountingList.addAllmain()lCountingList #1addCount3size0items[ ]size, items: MyList part (private)arr.length = 3 added

The subclass’s addAll adds the array length to the counter: 3. Then it hands the work to the superclass.

StackHeapMyList.addAllCountingList.addAllmain()lCountingList #1addCount3size0items[ ]size, items: MyList part (private)the MyList loop calls its own add()

MyList.addAll calls add(s), i.e. this.add(s), for each item. That is an implementation detail of the superclass.

StackHeapCountingList.addMyList.addAllCountingList.addAllmain()lCountingList #1addCount4size0items[ ]size, items: MyList part (private)this is a CountingList → overridden add

The object is a CountingList, so the call goes to the subclass’s add. The same item is counted a second time: 4.

StackHeapMyList.addCountingList.addMyList.addAllCountingList.addAllmain()lCountingList #1addCount4size1items[a]size, items: MyList part (private)super.add: the item is really added

super.add(s) stores the item in the array: size = 1.

StackHeapMyList.addAllCountingList.addAllmain()lCountingList #1addCount6size3items[a, b, c]size, items: MyList part (private)same path for "b" and "c"

"b" and "c" take the same path: each is counted once more. When the loop ends the counter is 6 and size is 3.

StackHeapmain()lCountingList #1addCount6size3items[a, b, c]size, items: MyList part (private)three items, count 6: fragile base class

Wrong result: 6 3. The subclass depended on how the superclass uses its own methods. If a new version of the superclass changed the loop, the result would change again: the fragile base class problem.

class MyList {
    private String[] items = new String[10];
    private int size;
    void add(String s) { items[size++] = s; }
    void addAll(String[] arr) {
        for (String s : arr) add(s);
    }
    int size() { return size; }
}
class CountingList extends MyList {
    int addCount = 0;
    @Override void add(String s) {
        addCount++;
        super.add(s);
    }
    @Override void addAll(String[] arr) {
        addCount += arr.length;
        super.addAll(arr);
    }
}
CountingList l = new CountingList();   // main
l.addAll(new String[] {"a", "b", "c"});
System.out.println(l.addCount + " " + l.size());

Relationships Between Classes

The Composition Fix: Forwarding

class CountingList2 {
    private final MyList list = new MyList(); // has-a
    private int addCount = 0;
    void add(String s) {
        addCount++;
        list.add(s);            // forwards
    }
    void addAll(String[] arr) {
        addCount += arr.length;
        list.addAll(arr);  // forwards
    }
    int getAddCount() { return addCount; }
    int size() { return list.size(); }
}
CountingList2 l2 = new CountingList2();
l2.addAll(new String[] {"a", "b", "c"});
System.out.println(l2.getAddCount()
    + " " + l2.size());
3 3
  • The new class does not extend MyList; it has a MyList. Each method does its own work first, then forwards the call to the inner object.
  • The add calls inside list.addAll(...) run on a plain MyList object; they never come back to CountingList2. The count is right: 3.
  • Even if MyList’s internals change, the result does not: the dependency is only on public methods.
  • The price: a CountingList2 cannot be passed where a MyList is expected. If needed, both implement a common interface.

Relationships Between Classes

The Liskov Substitution Principle (LSP)

class Rectangle {
    protected int width, height;
    void setWidth(int w) { width = w; }
    void setHeight(int h) { height = h; }
    int area() { return width * height; }
}
class Square extends Rectangle {
    @Override void setWidth(int k) { width = height = k; }
    @Override void setHeight(int k) { width = height = k; }
}
static void resize(Rectangle d) {
    d.setWidth(5);
    d.setHeight(4);
    System.out.println("Expected 20, got "
        + d.area());
}
// in main:
resize(new Rectangle());
resize(new Square());
Expected 20, got 20
Expected 20, got 16
  • Liskov substitution principle: code written against a superclass type must also work correctly with a subclass object. Compiling is not enough.
  • In mathematics every square is a rectangle. But this Rectangle class promises that “width and height change independently”; Square cannot keep that promise.
  • resize is not at fault; the fault lies in the subclass that breaks the promise.
  • Fixes: do not derive Square from Rectangle (both extend Shape), or make the classes immutable.
Apply the is-a test to the class’s behavior, not to the real world: “Can a Square answer every Rectangle method the way a Rectangle does?”

The Object Class

The Object Class

  • Every class extends java.lang.Object, indirectly if no extends is written.
  • So every object comes with the methods below ready to use.
  • Their default versions are rarely useful; meaningful classes override them.
class Point { }
// what the compiler sees:
class Point extends Object { }
MethodDefault behavior
String toString()Class name + @ + hashCode in hexadecimal
boolean equals(Object o)Compares references: this == o
int hashCode()An integer specific to the object (usually different for each object)
Class getClass()The object’s run-time class (final; cannot be overridden)

The Object Class

The toString Method

  • public String toString(): returns the object as text. println(obj) and "..." + obj call it automatically.
  • If not overridden, it returns a string with the class name and the object’s hashCode.

Not overridden

class Point {
    private int x, y;
    Point(int x, int y) {
        this.x = x; this.y = y;
    }
}
// in main
System.out.println(new Point(3, 4));
Point@28a418fc

The value after @ may change from run to run and means nothing to a reader. Printing a null reference does not call toString; it prints null.

Overridden

class Point {
    private int x, y;
    Point(int x, int y) {
        this.x = x; this.y = y;
    }
    @Override
    public String toString() {
        return "Point[x=" + x + ", y=" + y + "]";
    }
}
// in main
Point n = new Point(3, 4);
System.out.println(n);
System.out.println("Position: " + n);
Point[x=3, y=4]
Position: Point[x=3, y=4]

The Object Class · Step-by-step code trace

== or equals?

k1k2—k3—Person object #1name = "Ali"age = 25

new creates an object; k1 holds its address (reference).

k1k2k3—Person object #1name = "Ali"age = 25Person object #2name = "Ali"age = 25

Second new: same contents, but a separate object. k2 points to it.

k1k2k3Person object #1name = "Ali"age = 25Person object #2name = "Ali"age = 25

k3 = k1 copies no object, only the address. k1 and k3 point to the same object.

k1k2k3Person object #1name = "Ali"age = 25Person object #2name = "Ali"age = 25#1 ≠ #2 → false

== compares references: k1 and k2 point to different objects → false.

k1k2k3Person object #1name = "Ali"age = 25Person object #2name = "Ali"age = 25#1 = #1 → true

k1 and k3 point to the same object → true.

k1k2k3Person object #1name = "Ali"age = 25Person object #2name = "Ali"age = 25same contents → true

Since Person overrides equals, it compares the contents (name, age) → true. Without the override it would be false.

Person k1 = new Person("Ali", 25);
Person k2 = new Person("Ali", 25);
Person k3 = k1;
System.out.println(k1 == k2);
System.out.println(k1 == k3);
System.out.println(k1.equals(k2));

The Object Class

The equals Method

  • public boolean equals(Object other): tells whether two objects are equivalent.
  • By default it compares only references: unless overridden it behaves like the == operator.
  • Overriding changes this: the method should compare the two objects’ state (their fields) and return true if they are equal.
  • The parameter has type Object, so do a type check first to rule out bad cases.

The equals contract

Reflexivex.equals(x) → true
Symmetricx.equals(y) ⇔ y.equals(x)
Transitiveif x = y and y = z, then x = z
ConsistentThe result stays the same while the fields do not change
nullx.equals(null) → false
The same rule applies to String: compare with s1.equals(s2), not s1 == s2.
abPoint(3, 4) #1Point(3, 4) #2a == bfalseObject.equals (default)falseoverridden equalstrue

The Object Class

Writing equals

Type check with instanceof

public boolean equals(Object obj) {
    if (obj instanceof Point) {
        // obj is a Point;
        // cast and compare
        Point other = (Point) obj;
        return x == other.x && y == other.y;
    } else {
        // obj is not a Point;
        // cannot be equal
        return false;
    }
}
  • The parameter type must be Object; writing equals(Point n) is overloading, not overriding.
  • The cast (Point) obj is safe only after the type check.

Test

Point a = new Point(3, 4);
Point b = new Point(3, 4);
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(a.equals("3,4"));
System.out.println(a.equals(null));
false
true
false
false
"3,4" is not a Point → false. Since null instanceof Point is also false, no separate null check is needed.

The Object Class

equals with getClass()

public class Person {
    private String name;
    private int age;
    // ... constructor ...

    @Override
    public boolean equals(Object obj) {
        // same reference: equal
        if (this == obj) return true;
        // null or other class: not equal
        if (obj == null
                || getClass() != obj.getClass())
            return false;
        // compare the fields
        Person p = (Person) obj;
        return age == p.age
               && name.equals(p.name);
    }
}
  • this == obj: the same object returns true at once (fast path).
  • getClass() gives the object’s actual class; both sides must have exactly the same class.
  • Compare primitive fields (int age) with == and object fields (String name) with equals.
Type checkCan a subclass object count as equal?
instanceofYes (a Cat object is an Animal)
getClass()No (the classes must match exactly)

The Object Class · Step-by-step code trace

equals(): Code Trace

StackHeapmain()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age21

There are three separate objects. k1 and k2 have the same contents; k3 differs only in age.

StackHeapequals()thisobjp?main()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age21

k1.equals(k2): in the new frame this = #1 and obj = #2. The type of obj is Object.

StackHeapequals()thisobjp?main()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age21this == obj → false

this == obj compares addresses: #1 ≠ #2, so the fast path does not apply.

StackHeapequals()thisobjp?main()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age21null? false · Person != Person? false

obj is not null and getClass() is Person on both sides. The condition is false, so return false is skipped.

StackHeapequals()thisobjpmain()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age21

The downcast creates no new object: p points to the same #2, this time with type Person, so p.age can now be written.

StackHeapequals()thisobjpmain()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age2120 == 20 true && "Ali".equals("Ali") true

The primitive age is compared with ==, the String name with equals. Both hold: true.

StackHeapequals()thisobjp?main()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age21this == obj false · same class

k1.equals(k3): a new call with obj = #3. Different object, same class: on to the fields.

StackHeapequals()thisobjpmain()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age2120 == 21 false → name.equals not called

20 == 21 is false; && short-circuits and name.equals is never called. The result is false.

StackHeapequals()thisobjnullp?main()k1k2k3Person #1name"Ali"age20Person #2name"Ali"age20Person #3name"Ali"age21obj == null true → getClass() skipped

obj == null is true, so || skips its right side. Had obj.getClass() run, it would throw a NullPointerException.

public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null || getClass() != obj.getClass())
        return false;
    Person p = (Person) obj;
    return age == p.age && name.equals(p.name);
}
// in main:
Person k1 = new Person("Ali", 20);
Person k2 = new Person("Ali", 20);
Person k3 = new Person("Ali", 21);
System.out.println(k1.equals(k2));
System.out.println(k1.equals(k3));
System.out.println(k1.equals(null));

The Object Class

equals and hashCode

Rule: if you override equals, override hashCode too. Equal objects must have the same hashCode.
import java.util.Objects;
public class Point {
    private int x, y;
    public Point(int x, int y) {
        this.x = x; this.y = y;
    }
    @Override public boolean equals(Object o) {
        return (o instanceof Point n)
               && x == n.x && y == n.y;
    }
    @Override public int hashCode() {
        return Objects.hash(x, y);
    }
    @Override public String toString() {
        return "Point[x=" + x + ", y=" + y + "]";
    }
}

Why? HashSet and HashMap first pick a “bucket” by hashCode, then call equals. If the hashCodes differ, equal objects are never compared.

HashSet<Point> set = new HashSet<>();
set.add(new Point(3, 4));
set.add(new Point(3, 4));
System.out.println(set.size() + " "
    + set.contains(new Point(3, 4)));
In class PointOutput
only equals2 false ✗
equals + hashCode1 true ✓

The pattern o instanceof Point n requires Java 16+; the classic form is if (o instanceof Point) { Point n = (Point) o; … }.

The Object Class · Step-by-step code trace

equals and hashCode Inside a HashSet: Code Trace

set: 16 buckets (bucket = hash % 16)0123456789101112131415

An empty HashSet: each element goes into one of 16 buckets, chosen by hashCode().

set: 16 buckets (bucket = hash % 16)0123456789101112131415(3,4)Point(3,4)31·34 + 4 = 10581058 % 16 = 2 → bucket empty, added

hashCode() = 31·(31+3)+4 = 1058; 1058 % 16 = 2. The bucket is empty: the object is added.

set: 16 buckets (bucket = hash % 16)0123456789101112131415(3,4)(4,3)Point(4,3)31·35 + 3 = 10881088 % 16 = 0 → bucket empty, added

Same numbers, other order: hash 1088, bucket 0. Again an empty bucket, so it is added.

set: 16 buckets (bucket = hash % 16)0123456789101112131415(3,4)(4,3)new Point(3,4)1058 → bucket 2

A new Point(3, 4) object: hash 1058 again, the same bucket 2. The bucket is occupied, so equals is asked against its contents.

set: 16 buckets (bucket = hash % 16)0123456789101112131415(3,4)(4,3)new Point(3,4)equals → true3 == 3 && 4 == 4 → true: not added

equals is true: the set does not take the same element twice, and add returns false.

set: 16 buckets (bucket = hash % 16)0123456789101112131415(3,4)(4,3)

The set holds two elements: 2.

set: 16 buckets (bucket = hash % 16)0123456789101112131415(3,4)(4,3)new Point(4,3)1088 → bucket 0bucket 0 → equals true → foundwithout hashCode: other bucket, equals never asked

contains also finds the bucket first, then asks equals: true. Without hashCode, equal objects would land in different buckets.

public boolean equals(Object o) {
    if (!(o instanceof Point)) return false;
    Point n = (Point) o;
    return x == n.x && y == n.y;
}
public int hashCode() {
    return Objects.hash(x, y);  // 31·(31 + x) + y
}
// in main:
HashSet<Point> set = new HashSet<>();
set.add(new Point(3, 4));
set.add(new Point(4, 3));
set.add(new Point(3, 4));
System.out.println(set.size());
System.out.println(set.contains(new Point(4, 3)));

Summary

Summary

ConceptEssence
Inheritanceclass Child extends Parent; the subclass inherits the superclass members and adds new ones (is-a)
Not inheritedConstructors; private members exist in the object but cannot be reached directly
supersuper(...): superclass constructor (first line); super.m(): the superclass version
Constructor chainCompletes in the order Object → … → Parent → Child
OverridingSame signature, new body in the subclass; @Override lets the compiler check
protectedClass + subclasses + same package
finalMethod: cannot be overridden; class: cannot be extended
Has-aComposition: a field of another class type; composition and interfaces replace multiple inheritance
ObjectAncestor of every class; override toString, equals, hashCode
== / equalsCompare references / compare contents

Summary

Common Mistakes

Not calling super(...)

If the superclass has no no-arg constructor: constructor Animal in class Animal cannot be applied to given types.

Accessing a private field directly

health += 5; in the subclass: health has private access in Animal. Fix: a getter or a protected method.

Writing equals(Point)

If the parameter is not Object, it is an overload; with @Override: method does not override or implement a method from a supertype.

Comparing objects with ==

For two objects with the same contents == → false. Compare contents with equals, String included.

equals without hashCode

No compile error, but HashSet/HashMap misbehave: the same point is added twice.

Extending two classes

class D extends B, C → '{' expected. Fix: composition or an interface.

Narrowing access

If public void draw() becomes void draw() in the subclass: attempting to assign weaker access privileges.

Unchecked downcast

(Tire) p when p is not a Tire: ClassCastException. Check with instanceof first.

Summary

Common Mistakes (2)

this(...) and super(...) together

Both must be the first statement: call to super must be first statement in constructor. The constructor at the end of the chain calls super(...).

Changing the return type

String reproduce(): return type String is not compatible with Animal. Only a subtype (covariant) is allowed.

Thinking a private method is overridden

No error, but the superclass code still calls its own private version. @Override catches this mistake.

Reaching a protected member via a supertype reference

h.name in a subclass in another package: name has protected access in Animal. Access must go through the subclass’s own type.

Widening the exception list

void f() throws Exception when the superclass method has no throws: overridden method does not throw Exception.

Getting field order wrong

Subclass field initializers run after the superclass constructor finishes; while it runs, they still hold defaults.

Inheritance just to share code

If is-a does not hold, the subclass also gets unwanted public methods: Stack extends ArrayList allows inserting in the middle. Fix: composition.

Overriding a self-calling method

Other superclass methods may call the subclass version too: the counter goes up twice. Fix: read the superclass documentation, or use composition.

Summary

Practice Problems

class A {
    A() { System.out.println("A"); }
    void print() { System.out.println("A.print"); }
}
class B extends A {
    B() { System.out.println("B"); }
    @Override void print() { System.out.println("B.print"); }
}
class C extends B {
    C() { super(); System.out.println("C"); }
    @Override void print() {
        super.print();
        System.out.println("C.print");
    }
}
  1. What does C c = new C(); print?
  2. What does c.print(); print next?
  3. What does A a = new B(); a.print(); print?
  4. What is c instanceof A?
  5. In a Student class that does not override equals, what is o1.equals(o2) for two objects with the same name?
Show answers
  1. A B C: constructors complete top-down (B’s implicit super() runs A first).
  2. B.print, then C.print: super.print() calls B’s version.
  3. A B, then B.print: the variable has type A, but the object is a B, so B’s version runs.
  4. true: C extends A through B.
  5. false: Object’s equals compares references.

Summary

Practice Problems (2)

class A {
    static { System.out.print("As "); }
    { System.out.print("Ab "); }
    A() { System.out.print("A "); }
}
class B extends A {
    static { System.out.print("Bs "); }
    { System.out.print("Bb "); }
    B() { this(0); System.out.print("B "); }
    B(int x) { System.out.print("B" + x + " "); }
}
  1. What does the program’s first new B(); print? (Lines in plain braces are instance initializer blocks.)
  2. What does new B(7); print next?
  3. With the Square from the substitution example, what is d.area() after Rectangle d = new Square(); d.setHeight(4); d.setWidth(5);?
  4. Parent has protected Object copy(). Does @Override public Child copy() compile inside Child extends Parent?
Show answers
  1. As Bs Ab A Bb B0 B: static blocks run top-down on first use. Since the first line of B() is this(0), B’s instance block (Bb) runs only once, inside B(int) after super() returns.
  2. Ab A Bb B7: static blocks do not run again.
  3. 25: the last call is setWidth(5); Square sets both sides to 5.
  4. Yes: access widens (protected → public) and Child is a subtype of Object (covariant return).

Summary

Exercises

  1. Write Employee (name, salary) and a subclass Manager (bonus); add totalIncome() and a toString() that uses super.toString().
  2. Animal’s only constructor is Animal(String name). Write the constructor Bird(String name, boolean canFly).
  3. Write equals and hashCode for Student (int no, String name).
  4. Can a class in another package that is not a subclass access a protected field?
  5. is-a or has-a? Student–Person, Car–Wheel, Library–Book, Square–Shape.
Answers / hints
  1. Constructor: super(name, salary); this.bonus = bonus; · totalIncome(): getSalary() + bonus. new Manager("Ayşe", 50000, 8000) → 58000.0.
  2. Bird(String name, boolean canFly) { super(name); this.canFly = canFly; }
  3. if (!(o instanceof Student)) return false; Student s = (Student) o; return no == s.no && name.equals(s.name); · return Objects.hash(no, name);
  4. No: protected = class + same package + subclasses.
  5. is-a: Student–Person, Square–Shape · has-a: Car–Wheel, Library–Book.

Summary

References

  • Oracle, The Java Tutorials: Inheritance; Overriding and Hiding Methods; Using the Keyword super; Object as a Superclass.
  • J. Gosling et al., The Java Language Specification, Java SE 21 Edition (8.1.4 Superclasses and Subclasses, 8.4.8 Inheritance, Overriding, and Hiding).
  • P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 9: Object-Oriented Programming: Inheritance).
  • K. Sierra and B. Bates, Head First Java, 3rd ed., O'Reilly (Chapter 7: Inheritance and Polymorphism).
  • C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (Chapter 5: Inheritance).
  • J. Bloch, Effective Java, 3rd ed., Addison-Wesley (Items 10–11: equals and hashCode; Item 18: favor composition over inheritance).

The End

Chapter 4.3: Inheritance
Previous: Chapter 4.2: Encapsulation · Next: Chapter 4.4: Polymorphism
1 / 1 Sercan KÜLCÜ. All rights reserved.