Java Questions 31 - 40  «Prev  Next»

Overriding, Overloading Methods in Java

  1. What must be true for the access modifier of a subclass when it is overriding a method in the superclass?

    Answer:
    The overriding method cannot have a more restrictive access modifier than the method being overridden.
    You are allowed to override a method as long as the overiding method's access modifier is not more restrictive than the original one. This means you can do the following:
    Allowed:
    class Parent {
      public void aMethod() {
      }
    }
    class Child extends Parent {
      public void aMethod() {
      }
    }
    

    You are not allowed to do the following:
    Not Allowed:
    class Parent {
      public void aMethod() {
      }
    }
    class Child extends Parent {
      protected void aMethod() {
      }
    }
    
    In the above example, protected in the subclass is more restrictive than public in the superclass.

  2. What must be observed when overriding methods that throw exceptions?

    Answer:
    The overriding method must not throw checked exceptions that are new or broader than those declared by the overridden method.

  3. How does the JVM determine which method to run when a method is overridden?

    Answer:
    At runtime the JVM uses virtual method invocation to dynamically select the actual version of the method that will run, based on the actual instance.

  4. What is the relation between a superclass and subclass reference?

    Answer:
    A superclass reference can always refer to a subclass instance.

  5. What is the difference between method overriding and method overloading in Java?

    Answer:

    Method Overriding vs. Method Overloading in Java

    Both method overriding and method overloading are key concepts in Java that allow polymorphism, but they have fundamental differences in their behavior, implementation, and use cases.
    1. Method Overriding** Definition:Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. Key Characteristics:- Happens **between two classes** (parent and child class).
    • The method signature (name and parameters) remains the same.
    • Requires inheritance (i.e., a subclass must extend a superclass).
    • Uses the @Override annotation (optional but recommended).
    • The overridden method must have the same return type (or covariant return type).
    • The overridden method in the subclass cannot have a more restrictive access modifier than in the parent class.
    • Only instance methods can be overridden (not static or private methods).


    Example of Method Overriding
    class Parent {
        void showMessage() {
            System.out.println("Message from Parent class");
        }
    }
    
    class Child extends Parent {
        @Override
        void showMessage() {
            System.out.println("Message from Child class");
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            Parent obj = new Child();
            obj.showMessage();  // Output: Message from Child class
        }
    }
    

    Key Benefit:Enables **runtime polymorphism**, allowing dynamic method dispatch. --- ### **2. Method Overloading** **Definition:Method overloading occurs when multiple methods in the **same class** have the **same name** but **different parameters** (different number, type, or sequence of parameters).
    Key Characteristics:- Happens **within the same class**.
    • The method name remains the same, but the parameter list must be different.
    • Return type can be different, but it alone cannot differentiate methods.
    • Does not require inheritance.
    • Improves code readability and flexibility.

    Example of Method Overloading**
    class MathUtils {
        // Method with one parameter
        int add(int a) {
            return a + 10;
        }
    
        // Overloaded method with two parameters
        int add(int a, int b) {
            return a + b;
        }
    
        // Overloaded method with different parameter types
        double add(double a, double b) {
            return a + b;
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            MathUtils obj = new MathUtils();
            System.out.println(obj.add(5));         // Output: 15
            System.out.println(obj.add(5, 10));     // Output: 15
            System.out.println(obj.add(5.5, 4.5));  // Output: 10.0
        }
    }
    

    Key Benefit:Provides "compile-time polymorphism", allowing method calls to be resolved at compile time.
    Comparison Table: Overriding vs. Overloading**
    Feature Method Overriding Method Overloading
    Definition Redefining a method in a subclass Defining multiple methods with the same name but different parameters in the same class
    Where it Occurs Between superclass and subclass Within the same class
    Method Signature Must be exactly the same as in the parent class Must be different (varying parameters)
    Return Type Must be the same or a **covariant return type** Can be different but alone cannot differentiate methods
    Access Modifier Cannot be more restrictive than in the superclass Can have any access modifier
    Inheritance Required? Yes (between superclass and subclass) No (within the same class)
    Static Methods? Cannot be overridden (they are hidden instead) Can be overloaded
    Private Methods? Cannot be overridden Can be overloaded
    Final Methods? Cannot be overridden Can be overloaded
    Use Case Achieves runtime polymorphism Achieves compile-time polymorphism



    Key Takeaways
    • Overriding is for dynamic behavior (runtime polymorphism), whereas overloading is for flexible method invocation (compile-time polymorphism).
    • Overriding requires inheritance, while **overloading happens within the same class**.
    • Overriding must maintain method signature, while **overloading changes method parameters**.
    The overriding method must fulfill the contract of the superclass. Overloading occurs in Java when you have a different argument list.

  6. What will happen if the method of the subclass does not have the same arugment list as the method of the superclass?

    Answer:
    If the method of the subclass does not have the same argument list as the method of the superclass, you will overload instead of override the method.

  7. If a method in a subclass throws an exception, what must be true for the method in the superclass?

    Answer:
    General Rule: If the method in the subclass throws an exception, then the method in the superclass must also throw that exception.
    Example: If a method throws FileNotFoundException in a subclass, the overridden method in the superclass must throw the same exception.

  8. What is true about the overriding method of a subclass in relation to the method being overridden in the superclass?

    Answer:
    The overriding method must NOT throw checked exceptions that are broader (more encompassing) than those declared by the overridden method (in the superclass).

  9. What types of exceptions can the overriding method in the subclass throw?
    Answer:
    The overriding method can throw narrower or fewer exceptions.

  10. What is the relationship between a superclass and a subclass when it comes to throwing exceptions in Java?

    Answer:
    A method in the superclass may throw an exception. However, the overriding method in the subclass does not have to throw that same exception.

SEMrush Software