Chapter 4.3: Inheritance
Introduction
Learning Outcomes
Define inheritance, superclass and subclass; recognize the “is-a” relationship.
Write a subclass with extends; explain what is inherited and what is not.
Use super(...) and super.method(); trace the order of the constructor chain.
Override a method, tell overriding from overloading, and use @Override.
Explain protected access and how final restricts inheritance.
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.
width, height and area().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.extendsmeans “builds on”. extendsnames exactly one class.- The subclass uses the superclass’s
publicandprotectedmembers 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
extendsimplicitly extendsObject.
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
Objectclass in packagejava.lang. - Every class inherits from
Object, directly or indirectly.
The Idea of Inheritance
Kinds of Inheritance
- Single: one subclass, one superclass.
Cat extends Animal. - Multilevel: a chain.
Catgets the members ofLivingThingthroughAnimal; 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.
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.The Idea of Inheritance
What Is Inherited?
| Member | Inherited by the subclass? | Note |
|---|---|---|
public / protected fields and methods | Yes | Used directly in the subclass. |
| Members with no modifier (package access) | Only within the same package | A subclass in another package cannot access them. |
private fields | Present in the object, but not directly accessible | Used through the superclass’s public/protected methods (getters, setters). |
private methods | No | Invisible; cannot be overridden. |
| Constructors | No | Not inherited; the subclass constructor calls them with super(...). |
static members | Accessible | Belong 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; onlyCat’s code cannot name them. superis not a separate object: it is a way to reach the superclass part of the same object through the superclass’s code.
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
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
Superclass methods and fields are used in the subclass without being rewritten.
An existing class gains new features without changing its code.
Superclass methods can be changed in the subclass by overriding them.
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
namefield itself; it leaves that tosuper(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
The object is a Cat; lookup starts at the bottom and finds Cat.introduce().
super.introduce() calls the version one level up. Cat.introduce waits on the stack.
The object is still a Cat, yet super inside Animal always means LivingThing: no dynamic binding.
The topmost version runs and prints the first line, then returns.
Animal.introduce() resumes where it left off: I'm an animal.
Finally Cat.introduce() prints its own line.
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)
new: memory for the object is allocated first; all fields (Animal’s included) get default values.
The Cat constructor is called. Before it does its own work, the superclass part must be ready.
super(name): the Animal constructor is called; the Cat constructor waits.
Animal first calls its own superclass: Object(). Every chain ends at Object.
Object() returns. Animal fills its own field: name = "Mavi".
health = 100.0.
The Animal constructor prints its message and returns: the superclass printed first.
The Cat constructor resumes: indoor = true.
The Cat constructor prints its message.
The constructor is done; the object’s address is stored in cat.
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
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.
Constructors and super · Step-by-step code trace
this(...) and super(...): Code Trace
new first allocates the object; all three fields hold default values. Then Manager(String) is called.
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.
super(name): the one-argument constructor of the superclass Employee. Building the Manager part waits until the Employee part is done.
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.
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.
The two-argument constructor returned; Employee(String) prints its line.
super(name) is done. Only now does the subclass set its own field: bonus = 5000.0.
Finally the first one called, Manager(String), finishes. Four constructors ran, but only one object was built.
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
For the first new Child(), the JVM must initialize class Child. The superclass goes first: Parent’s static block runs.
Then Child’s static block. Class initialization happens once per program run.
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(...).
Then the Parent() body. At this point b is still 0: the Child part has not been initialized at all.
After super() returns, the subclass field initializers run: b = value("Child field").
Last comes the Child() body. Order: superclass fields → superclass constructor → subclass fields → subclass constructor.
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
publicmethod stayspublic. final,staticandprivatemethods 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
| Overriding | Overloading | |
|---|---|---|
| Where? | In a subclass, for an inherited method | In the same class (or a subclass) |
| Name | Same | Same |
| Parameters | Same | Different (number or type) |
| Return type | Same or a subtype | Any |
| Purpose | Change inherited behavior | Do the same job with different inputs |
| Resolved at | Run 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
@Overrideis 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
| Aspect | Allowed in the subclass | javac if broken |
|---|---|---|
| Name and parameters | Exactly the same | No error: a new method (overload) |
| Return type | Same or a subtype (covariant) | return type String is not compatible with Animal |
| Access | Same or wider: protected → public | attempting to assign weaker access privileges |
| Checked exceptions | Same, more specific, or none | overridden method does not throw Exception |
static | Cannot switch between instance and static | overriding method is static / overridden method is static |
final method | Cannot be overridden | overridden method is final |
private method | Invisible; a same-named method is unrelated | No error (error with @Override) |
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
Catreference gets aCatdirectly; no(Cat)cast is needed. - A caller holding an
Animalreference loses nothing: aCatis also anAnimal. - This works only for reference types; you cannot return
longinstead ofint.
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
privatemethod is invisible to subclasses; a same-named subclass method is an unrelated new one. - In
Parent.call(),greet()is bound at compile time toParent’sprivatemethod, soParent.greetis printed even for aChild. - Using
@Overridecatches this at compile time.
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)
Foodchanges onlytaxRate();salePrice()andtoString()are not written there, yet they use 1%, because the call insideProductis chosen by the object’s class.SaleProductdoes not replace the superclass computation, it extends it: it applies the discount tosuper.salePrice(). 1000 × 1.20 × 0.75 = 900.
Access and Restriction
The protected Access Level
| Modifier | Same class | Same package | Subclass (other package) | Everywhere |
|---|---|---|---|---|
private | ✓ | ✗ | ✗ | ✗ |
| (none: package) | ✓ | ✓ | ✗ | ✗ |
protected | ✓ | ✓ | ✓ | ✗ |
public | ✓ | ✓ | ✓ | ✓ |
public: the members are accessible from everywhere.private: only from inside the class.protectedsits between the two: the class itself, its subclasses and other classes in the same package can access it.- A subclass can reach the
privatefields of its superclass only through inheritedpublicorprotectedmethods.
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
protectedmember only through a reference of its own type (or its subtypes):nameandk.nameare fine. h, however, may point to anyAnimal, aDogfor example.Catis not allowed to touch the internals of another subclass.- Classes in the same package have no such restriction: there,
protectedincludes package access.
Access and Restriction
Restricting Inheritance with final
- The
finalkeyword can be used to restrict inheritance. - A
finalmethod cannot be overridden in any subclass. - No class can extend a
finalclass. 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
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).
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 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.
// 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
new Car(90): one object, holding speed from the superclass Vehicle and its own engine field (is-a).
The constructor creates a second object: a car is not an engine, it has one (has-a). The link is a reference.
drive() runs on the Car object.
engine.start(): Car does not do the work itself; it follows the reference and delegates to the Engine object.
accelerate(50) is not written in Car; it is inherited from Vehicle and sets the same object’s speed to 50.
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).
class D extends B, C { } // invalid
error: '{' expectedinterface Chargeable { void charge(); } class ElectricCar extends Car implements Chargeable { @Override public void charge() { System.out.println("Charging."); } }
Relationships Between Classes
Design Principles for Inheritance
If “every X is a Y” is false, do not use inheritance. A Car is not an Engine; it has one → composition.
Superclass fields get their values through super(...) and superclass methods; fields stay private.
Every meaningful class should override toString and equals (and, with it, hashCode).
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) | |
|---|---|---|
| Relationship | is-a: “every X is a Y” | has-a: “an X has a Y” |
| Coupling | Tight: the subclass depends on the superclass’s implementation too | Loose: depends only on the inner object’s public methods |
| Reuse | Automatic: every public method comes along (wanted or not) | Selective: you write only the methods you want to forward |
| Change | The superclass is fixed at compile time | The field can be swapped for another object at run time |
| Use in place of the supertype | Directly: Animal h = new Cat() | If both implement a common interface |
when the is-a relationship truly holds and the superclass was designed and documented for extension: Cat – Animal.
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
CountingList extends MyList to count the items added. Both add methods are overridden.
The subclass’s addAll adds the array length to the counter: 3. Then it hands the work to the superclass.
MyList.addAll calls add(s), i.e. this.add(s), for each item. That is an implementation detail of the superclass.
The object is a CountingList, so the call goes to the subclass’s add. The same item is counted a second time: 4.
super.add(s) stores the item in the array: size = 1.
"b" and "c" take the same path: each is counted once more. When the loop ends the counter is 6 and size is 3.
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 aMyList. Each method does its own work first, then forwards the call to the inner object. - The
addcalls insidelist.addAll(...)run on a plainMyListobject; they never come back toCountingList2. The count is right: 3. - Even if
MyList’s internals change, the result does not: the dependency is only onpublicmethods. - The price: a
CountingList2cannot be passed where aMyListis 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
Rectangleclass promises that “width and height change independently”;Squarecannot keep that promise. resizeis not at fault; the fault lies in the subclass that breaks the promise.- Fixes: do not derive
SquarefromRectangle(both extendShape), or make the classes immutable.
The Object Class
The Object Class
- Every class extends
java.lang.Object, indirectly if noextendsis 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 { }
| Method | Default 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"..." + objcall 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?
new creates an object; k1 holds its address (reference).
Second new: same contents, but a separate object. k2 points to it.
k3 = k1 copies no object, only the address. k1 and k3 point to the same object.
== compares references: k1 and k2 point to different objects → false.
k1 and k3 point to the same object → 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
trueif they are equal. - The parameter has type
Object, so do a type check first to rule out bad cases.
The equals contract
| Reflexive | x.equals(x) → true |
| Symmetric | x.equals(y) ⇔ y.equals(x) |
| Transitive | if x = y and y = z, then x = z |
| Consistent | The result stays the same while the fields do not change |
| null | x.equals(null) → false |
String: compare with s1.equals(s2), not s1 == s2.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; writingequals(Point n)is overloading, not overriding. - The cast
(Point) objis 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 returnstrueat 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) withequals.
| Type check | Can a subclass object count as equal? |
|---|---|
instanceof | Yes (a Cat object is an Animal) |
getClass() | No (the classes must match exactly) |
The Object Class · Step-by-step code trace
equals(): Code Trace
There are three separate objects. k1 and k2 have the same contents; k3 differs only in age.
k1.equals(k2): in the new frame this = #1 and obj = #2. The type of obj is Object.
this == obj compares addresses: #1 ≠ #2, so the fast path does not apply.
obj is not null and getClass() is Person on both sides. The condition is false, so return false is skipped.
The downcast creates no new object: p points to the same #2, this time with type Person, so p.age can now be written.
The primitive age is compared with ==, the String name with equals. Both hold: true.
k1.equals(k3): a new call with obj = #3. Different object, same class: on to the fields.
20 == 21 is false; && short-circuits and name.equals is never called. The result is false.
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
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 Point | Output |
|---|---|
only equals | 2 false ✗ |
equals + hashCode | 1 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
An empty HashSet: each element goes into one of 16 buckets, chosen by hashCode().
hashCode() = 31·(31+3)+4 = 1058; 1058 % 16 = 2. The bucket is empty: the object is added.
Same numbers, other order: hash 1088, bucket 0. Again an empty bucket, so it is added.
A new Point(3, 4) object: hash 1058 again, the same bucket 2. The bucket is occupied, so equals is asked against its contents.
equals is true: the set does not take the same element twice, and add returns false.
The set holds two elements: 2.
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
| Concept | Essence |
|---|---|
| Inheritance | class Child extends Parent; the subclass inherits the superclass members and adds new ones (is-a) |
| Not inherited | Constructors; private members exist in the object but cannot be reached directly |
super | super(...): superclass constructor (first line); super.m(): the superclass version |
| Constructor chain | Completes in the order Object → … → Parent → Child |
| Overriding | Same signature, new body in the subclass; @Override lets the compiler check |
protected | Class + subclasses + same package |
final | Method: cannot be overridden; class: cannot be extended |
| Has-a | Composition: a field of another class type; composition and interfaces replace multiple inheritance |
| Object | Ancestor of every class; override toString, equals, hashCode |
== / equals | Compare references / compare contents |
Summary
Common Mistakes
If the superclass has no no-arg constructor: constructor Animal in class Animal cannot be applied to given types.
health += 5; in the subclass: health has private access in Animal. Fix: a getter or a protected method.
If the parameter is not Object, it is an overload; with @Override: method does not override or implement a method from a supertype.
For two objects with the same contents == → false. Compare contents with equals, String included.
No compile error, but HashSet/HashMap misbehave: the same point is added twice.
class D extends B, C → '{' expected. Fix: composition or an interface.
If public void draw() becomes void draw() in the subclass: attempting to assign weaker access privileges.
(Tire) p when p is not a Tire: ClassCastException. Check with instanceof first.
Summary
Common Mistakes (2)
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(...).
String reproduce(): return type String is not compatible with Animal. Only a subtype (covariant) is allowed.
No error, but the superclass code still calls its own private version. @Override catches this mistake.
h.name in a subclass in another package: name has protected access in Animal. Access must go through the subclass’s own type.
void f() throws Exception when the superclass method has no throws: overridden method does not throw Exception.
Subclass field initializers run after the superclass constructor finishes; while it runs, they still hold defaults.
If is-a does not hold, the subclass also gets unwanted public methods: Stack extends ArrayList allows inserting in the middle. Fix: composition.
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"); } }
- What does
C c = new C();print? - What does
c.print();print next? - What does
A a = new B(); a.print();print? - What is
c instanceof A? - In a
Studentclass that does not overrideequals, what iso1.equals(o2)for two objects with the same name?
Show answers
- A B C: constructors complete top-down (B’s implicit
super()runs A first). - B.print, then C.print:
super.print()calls B’s version. - A B, then B.print: the variable has type A, but the object is a B, so B’s version runs.
- true: C extends A through B.
- false: Object’s
equalscompares 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 + " "); } }
- What does the program’s first
new B();print? (Lines in plain braces are instance initializer blocks.) - What does
new B(7);print next? - With the
Squarefrom the substitution example, what isd.area()afterRectangle d = new Square(); d.setHeight(4); d.setWidth(5);? Parenthasprotected Object copy(). Does@Override public Child copy()compile insideChild extends Parent?
Show answers
- As Bs Ab A Bb B0 B: static blocks run top-down on first use. Since the first line of
B()isthis(0),B’s instance block (Bb) runs only once, insideB(int)aftersuper()returns. - Ab A Bb B7: static blocks do not run again.
- 25: the last call is
setWidth(5);Squaresets both sides to 5. - Yes: access widens (
protected→public) andChildis a subtype ofObject(covariant return).
Summary
Exercises
- Write
Employee(name,salary) and a subclassManager(bonus); addtotalIncome()and atoString()that usessuper.toString(). Animal’s only constructor isAnimal(String name). Write the constructorBird(String name, boolean canFly).- Write
equalsandhashCodeforStudent(int no,String name). - Can a class in another package that is not a subclass access a
protectedfield? - is-a or has-a? Student–Person, Car–Wheel, Library–Book, Square–Shape.
Answers / hints
- Constructor:
super(name, salary); this.bonus = bonus;·totalIncome():getSalary() + bonus.new Manager("Ayşe", 50000, 8000)→ 58000.0. Bird(String name, boolean canFly) { super(name); this.canFly = canFly; }if (!(o instanceof Student)) return false; Student s = (Student) o; return no == s.no && name.equals(s.name);·return Objects.hash(no, name);- No: protected = class + same package + subclasses.
- 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).