← Back to quizzesFree quiz

Java Polymorphism, Overriding and Equality

Java’s object‑oriented nature relies heavily on polymorphism , the ability of a single reference type to refer to objects of multiple concrete classes. Two core mechanisms that enable…

10 questions~5 min
Java Polymorphism, Overriding and Equality — Qwi
0 / 10
Score: 0%
1

When a subclass overrides a method, which statement about the overridden method's accessibility is correct?

2

Given class Dog extends Animal and overrides toString() to return name, what will System.out.println(dog) output if name is "Fido"?

3

Which of the following best describes the purpose of using super.toString() inside an overridden toString() method?

4

In the Ball class example, what value is printed by moveTo(30, 40) given the fields x=10, y=10?

5

Why is it generally advisable to override equals(Object o) in your own classes?

6

Which statement correctly distinguishes method overloading from overriding?

7

What will the expression "new String("abc").equals(new String("abc"))" evaluate to?

8

If class Student extends Person and defines void printInformation(String personalInformation, String grades), which concept does this illustrate?

9

Which of the following is a correct way to compare two int arrays for equality?

10

What is the effect of declaring a local variable with the same name as an instance variable inside a method?

Understanding Java Polymorphism, Overriding, and Equality

Java’s object‑oriented nature relies heavily on polymorphism, the ability of a single reference type to refer to objects of multiple concrete classes. Two core mechanisms that enable polymorphism are method overriding and method overloading. In addition, correctly implementing equals(Object) and hashCode() is essential for logical equality and collection behavior. This course breaks down each concept, explains common pitfalls, and provides practical examples that mirror real‑world interview questions.

1. Method Overriding and Visibility Rules

When a subclass provides its own implementation of a method declared in a superclass, it overrides that method. Overriding is subject to strict visibility constraints:

  • Rule: The overriding method must have the same or higher visibility than the method it replaces.
  • It cannot be declared more private.
  • Typical visibility levels (from most restrictive to most permissive) are: private → package‑private → protected → public.

For example, if a superclass method is protected, the subclass may declare it as protected or public, but not private. This rule preserves the Liskov Substitution Principle, ensuring that code expecting the superclass’s contract continues to work with the subclass instance.

2. Overriding toString() for Meaningful Output

The default implementation of Object.toString() returns a string that looks like ClassName@hashcode. Overriding toString() allows developers to present a human‑readable description of an object’s state.

Consider the following classes:

class Animal { }

class Dog extends Animal {
    private String name;
    public Dog(String name) { this.name = name; }
    @Override
    public String toString() { return name; }
}

When we execute:

Dog dog = new Dog("Fido");
System.out.println(dog);

the output is "Fido", because the overridden toString() returns the name field instead of the default identity string.

3. Using super.toString() Inside an Override

Sometimes you want to keep the superclass’s representation and add extra information. The super keyword lets you invoke the parent’s version of a method.

@Override
public String toString() {
    return super.toString() + " (name=" + name + ")";
}

Here, super.toString() provides the original string (perhaps the class name and hash code), and the subclass appends its own state. This pattern is common when extending classes that already implement a useful toString() but need additional context.

4. Method Overloading vs. Overriding

Both concepts involve methods with the same name, but they differ fundamentally:

  • Overloading occurs within the same class (or across a class hierarchy) when multiple methods share a name but have different parameter lists (type, number, or order). The compiler determines which method to call at compile time.
  • Overriding replaces a superclass method with a new implementation that has the exact same signature (name, parameters, and return type). The JVM selects the appropriate method at runtime based on the actual object type.

Example of overloading:

class Student extends Person {
    public void printInformation(String personalInformation) { … }
    public void printInformation(String personalInformation, String grades) { … }
}

Because the parameter lists differ, this is method overloading, not overriding.

5. Implementing Logical Equality with equals(Object)

The default equals() method from Object checks for reference equality (i.e., ==). For most domain objects, we need value equality—two distinct instances that represent the same logical entity should be considered equal.

Why override equals(Object)?

  • It enables meaningful comparisons in collections such as Set or Map.
  • It allows developers to write code like if (student.equals(otherStudent)) … that reflects business rules.
  • When equals is overridden, hashCode must also be overridden to maintain the contract required by hash‑based collections.

Typical implementation pattern:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Student)) return false;
    Student s = (Student) o;
    return Objects.equals(id, s.id) && Objects.equals(name, s.name);
}

@Override
public int hashCode() {
    return Objects.hash(id, name);
}

This code compares the id and name fields, providing logical equality based on state rather than identity.

6. Equality of String Objects

Java’s String class overrides equals(Object) to compare the character sequences of two strings. Therefore, the expression:

new String("abc").equals(new String("abc"))

evaluates to true, even though the two objects occupy different memory locations. This demonstrates that equals can be overridden to provide value‑based comparison, a principle you should apply to your own classes.

7. Practical Example: The Ball Class

Consider a simple class that tracks a ball’s position:

class Ball {
    private int x = 10;
    private int y = 10;
    public String moveTo(int newX, int newY) {
        return "moving ball to " + newX + "+" + newY;
    }
}

Calling moveTo(30, 40) prints moving ball to 30+40. The method does not modify the internal fields; it merely returns a formatted string based on the supplied arguments.

8. Polymorphic Dispatch in Action

Polymorphism shines when a reference of a superclass type points to a subclass object:

Animal a = new Dog("Fido");
System.out.println(a.toString()); // Calls Dog's overridden toString()

The JVM determines at runtime that the actual object is a Dog, so the overridden toString() executes. This dynamic method dispatch is the essence of runtime polymorphism.

9. Key Takeaways for Interview Preparation

  • When overriding, never reduce visibility; you may keep it the same or broaden it.
  • Always use @Override annotation to catch signature mismatches early.
  • Override toString() to provide useful debugging information.
  • Use super.toString() when you want to extend, not replace, the superclass representation.
  • Distinguish overloading (different parameters) from overriding (same signature).
  • Implement equals(Object) and hashCode() together for logical equality.
  • Remember that String.equals() compares content, not reference.

10. Frequently Asked Questions (FAQ)

Can an overriding method be declared private?

No. A private method is not visible to subclasses, so it cannot be overridden. The overriding method must be at least as visible as the original.

What happens if I forget to override hashCode() after overriding equals()?

Hash‑based collections (e.g., HashSet) may behave unpredictably because equal objects could end up in different buckets, violating the contract that equal objects must have identical hash codes.

Is method overloading resolved at compile time or runtime?

Overloading is a compile‑time (static) decision based on the argument types. Overriding, on the other hand, is resolved at runtime (dynamic dispatch).

Why do we use super in an overridden method?

The super keyword lets you reuse the superclass’s behavior, avoiding code duplication and preserving existing functionality while adding new details.

11. Best Practices Checklist

  • Always annotate overriding methods with @Override.
  • Maintain or increase visibility when overriding.
  • Provide a clear, concise toString() that reflects the object's state.
  • When overriding equals, also override hashCode using the same fields.
  • Prefer composition over inheritance when you need to reuse behavior without the pitfalls of deep inheritance hierarchies.
  • Write unit tests for equals, hashCode, and toString to guarantee correctness.

12. Conclusion

Mastering Java’s polymorphic features—method overriding, overloading, and proper equality handling—empowers you to write clean, maintainable, and performant code. By adhering to visibility rules, leveraging super wisely, and implementing logical equality, you’ll avoid common bugs and impress interviewers with a deep understanding of object‑oriented principles.