LearnFrenzy
Sign in Take a free test

Java Programming · Topic 13 of 28

Polymorphism and Method Overriding

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Polymorphism and Method Overriding · Study material

Replacing conditionals with polymorphism

When code branches on "what kind of thing is this?", move each branch into a class of its own. Adding a new kind then means adding a class, not editing every if/else.

import java.util.List;

public class Main {
    // ✘ Without polymorphism: every new type means editing this method
    static double shippingIf(String type, double kg) {
        if (type.equals("standard")) return 40 + 10 * kg;
        else if (type.equals("express")) return 80 + 20 * kg;
        else if (type.equals("pickup")) return 0;
        throw new IllegalArgumentException(type);
    }

    // ✔ With polymorphism: each type knows its own rule; new types need no changes here
    interface Shipping { double cost(double kg); String name(); }
    static class Standard implements Shipping { public double cost(double kg) { return 40 + 10 * kg; } public String name() { return "standard"; } }
    static class Express implements Shipping { public double cost(double kg) { return 80 + 20 * kg; } public String name() { return "express"; } }
    static class Pickup implements Shipping { public double cost(double kg) { return 0; } public String name() { return "pickup"; } }

    public static void main(String[] args) {
        for (Shipping s : List.of(new Standard(), new Express(), new Pickup())) {
            System.out.println(s.name() + " " + s.cost(2.5) + " " + (s.cost(2.5) == shippingIf(s.name(), 2.5)));
        }
    }
}

Output

standard 65.0 true
express 130.0 true
pickup 0.0 true

Overriding equals, hashCode and toString correctly

final class Point {
    private final int x, y;
    Point(int x, int y) { this.x = x; this.y = y; }

    @Override                                   // Object.equals takes an Object – not a Point!
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point p)) return false;
        return x == p.x && y == p.y;
    }

    @Override public int hashCode() { return 31 * x + y; }        // always together with equals
    @Override public String toString() { return "(" + x + ", " + y + ")"; }
}

Programming to the supertype

// ✔ Declare variables, parameters and return types with the most general useful type
List<String> names = new ArrayList<>();          // can switch to LinkedList without other changes
Map<String, Integer> stock = new HashMap<>();
void notifyAll(Collection<? extends Notifier> notifiers) { … }
Payment choosePayment(String mode) { … }        // returns UpiPayment, CardPayment …

// ✘ Tied to one implementation
ArrayList<String> names2 = new ArrayList<>();

Polymorphism checklist

  • Put @Override on every overriding method.
  • Keep the overriding method's contract: same meaning, no surprises (Liskov).
  • Use super.method() to extend behaviour.
  • Do not rely on fields or static methods behaving polymorphically.
  • Program to interfaces and superclasses.
  • Prefer overriding over instanceof chains; use sealed types + switch when operations vary more than types.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links