Sunday, September 24, 2023

19 Java and OOP Method Overloading and Overriding Interview Questions and Answers

Method overloading and overriding are some of the tricky concepts to master and that's why it's one of the most popular topics in Java Interviews. You will often see questions like what is the difference between overloading and overriding? or can you overload methods in the same class? during the first few rounds of interviews, mostly at telephonic rounds. Since it's part of object-oriented fundamentals it's also good to know as much about these concepts as possible. In this article, I am sharing some of the basic but frequently asked questions which are solely based upon overloading and overriding concept and their implementation in Java programming language. 

By going through these questions, You will not only do well on interviews but also it will improve your understanding of Java and OOP fundamentals. 


Btw, if you are seriously preparing for Java interviews, just preparing this topic will not be enough and you need to prepare other important topics as well like Java Collection framework, multi-threading, JVM internals, and garbage collections etc. 

If you are in hurry, I would suggest you take a look at the Java Programming Interview Exposed by Wrox publication, one of the better books on Java interviews.



Java and OOP Overloading and Overriding Interview Questions

Ok, let's start with questions. Here is my list of 17 method overloading and overriding interview question which covers basics as well as some tricky parts of overloading and overriding. You can also write some code to test the concept and see when the compiler gives an error and which method is get called at run-time.



1) What is method overloading in Java?
If you have two methods which do the same thing it's better they have the same name, but two methods cannot have the same name until you overload them. 

So overloading is a process of declaring two methods with the same name but different method signature like System.out which is object of PrintStream class has several println() method to print different data types e.g. byte, short, int, char, float and double. All of them are called the overloaded method. 

Overloaded method calls are resolved during compile time in Java and they must have different method signatures. See here to learn more about method overloading in Java.


2) What is method overriding in Java?
Method overriding is another way to define a method with same name but different code but it must be in subclass. Overriding is based upon run-time Polymorphism as method calls are resolved at run-time depending upon actual object.  

For example if a variable of type Parent holds an object of Child class then method invoked will be from child class and not parent class, provides its overridden. 

In order to override a method, you must follow rules of method overriding which means declaring method with same signature in sub class. See here to learn more about method overriding in Java.


3) What is method hiding in Java?
static method cannot be overriding in Java because their method calls are resolved at compile time but it didn't prevent you from declaring method with same name in sub class. In this case we say that method in sub class has hidden static method from parent class. 

If you have a case where variable of Parent class is pointing to object of Child class then also static method from Parent class is called because overloading is resolved at compile time. See here to learn more about method hiding in Java.


4) What are the rules of overloading a method in Java?
One and only rule of method overloading in Java is that the method signature of all overloaded method must be different. 

Method signature is changed by changing either number of method arguments, or type of method arguments e.g. System.out.println() method is overloaded to accept different primitive types like int, short, byte, float etc.

They all accept just one argument but their type is different. You can also change method signature by changing order of method argument but that often leads to ambiguous code so better to be avoided. See here for full list of rules.


5) Difference between method overloading and overriding?
The fundamental difference between overloading and overriding is that formerly took place during compile time while later took place during run-time. 

Due to this reason, its only possible to overload virtual methods in Java. You cannot overload methods which are resolved during compile time e.g. private, static and final method cannot be overridden in Java. 

Also, rules of method overloading and overriding are different, for example in order to overload a method its method signature must be different but for the overriding method, it must be the same. See this image to learn more difference between overriding and overloading in Java.

Method overloading and overriding interview questions and answers


6) Can we overload static method in Java?
Yes, its possible to overload static method in Java. You can declare as many static method with same name as you want until all of them have different method signature. Remember, return type is not part of method signature, so they must have either different number of arguments, or different type of argument. 

There is a third option also which changes order of argument but I suggest not to do that because it often result in the ambiguous method call. It's very important to follow these best practices while overloading a static method in Java.


7) Can we override static method in Java?
No, you cannot override static method in Java because they are resolved and bonded during compile time. Since overriding is a run-time activity and if a method call is already resolved at compile time then it will not take place and that's why it's not possible to override static method in Java. 

But, you can define another static method of same signature in sub class, this is known as method hiding. Actual method called will depends upon the type of class and not on type of object as its the case with overriding. See here to learn more about why you cannot override static method in Java.


8) Can you prevent overriding a method without using final modifier?
Yes, there are some funky ways to prevent method overriding in Java. Though final modifier is only for that purpose you can use private keyword to prevent method overriding. How? If you remember correctly, in order to override a method, the class must be extensible. 

If you make the constructor of parent class private then its not possible to extend that class because its constructor will not be accessible in sub class, which is automatically invoked by sub class constructor, hence its not possible to override any method from that class. 

This technique is used in Singleton design pattern, where constructor is purposefully made private and a static getInstance() method is provided to access singleton instance. See here to learn more techniques to prevent method overriding in Java.


9) Can we override a private method in Java?
No, you cannot override private method in Java. Since private methods are not visible outside the class, they are not available in sub-class hence they cannot be overridden. By the way, how about overriding a private method inside an Inner class? Is it possible? See here to learn more why you cannot override private method in Java.


10) What is covariant method overriding?
One of the rule of method overriding is that return type of overriding method must be same as overridden method but this restriction is relaxed little bit from Java 1.5 and now overridden method can return sub class of return type of original method. 

This relaxation is known as co-variant method overriding and it allows you to remove casting at client end. 

One of the best examples of this comes when you override clone() method. Original Object.clone() method returns Object which needs to cast, but with co-variant method overriding you can directly return relevant type e.g. Date class returns object of java.util.Date instead of java.lang.Object. See here to learn more about co-variant method overriding in Java.


11) Can we change argument list of overridden method?
No, you cannot change the argument list of overridden method in Java. An overriding method must have same signature as original method. Only return type can be changed that to only to sub type of return type of original method.


12) Can we change return type of method in subclass while overriding?
No, you cannot change the return type of method during overriding. It would be violation of rules of overriding. Though from Java 5 onward you can replace the return type with sub type e.g. if original method has return type as java.lang.Object then you can change return type of overridden method as any type e.g. clone() method. This is also known as co-variant method overriding in Java.


13) Can we override a method which throws run-time exception without throws clause?
Yes, you can. There is no restriction on throwing RuntimeException from overriding method. So if your original method throws NullPointerException than its not necessary to throw NPE from overriding method as well.


14) How do you call super class version of an overriding method in sub class?
You can call it using super keyword. For example if you have a method calculate() in both parent and child class then from child class you can invoke parent class method calculate() as super.calculate(). It's very similar to calling super class constructor from sub class as shown here.


15) What are rules of method overriding in Java?
Some rules of method overriding are following :
  • Overriding method cannot throw higher exception than overridden one, but that's only true for checked exception.
  • Overriding method cannot restrict access of overridden method e.g. if original method is public then overriding method must be public, but it can expand access e.g. if original method is protected than overriding method can be protected or public.
See here for full list of rules of method overriding in Java.


16) Can we override a non-static method as static in Java?
No, its not possible to define a non-static method of same name as static method in parent class, its compile time error in Java. See here to learn more about the overriding static method in Java.


17) Can we override the constructor in Java?
No, you cannot override constructors in Java because they are not inherited. Remember, we are talking about overriding here not overloading, you can overload construct but you cannot override them.

Overriding always happens in child class and since constructors are not inherited and their name is always the same as the class name it's not possible to override them in Java, to learn more about constructors see here


18) Can we override a final method in Java?
No, you cannot override a final method in Java. Trying to override a final method in a subclass will result in a compile-time error. Actually making a method final is signal to all developer that this method is not for inheritance and it should be used in its present form. You generally make a method final due to security reasons, to learn more see here.


19) Can you overload or override the main method in Java?
Since main() is a static method in Java, it follows rules associated with the static method, which means you can overload the main method but you cannot override it. 

By the way, even if you overload the main method, JVM will always call the standard public static void main(String args[]) method to start your program, if you want to call your overloaded method you need to do it explicitly in your code as shown here.


That's all about some Java interview questions from method overloading and overriding concept. I must admit it a tricky concept to master. I have seen even experienced developers struggling to solve quiz and multiple-choice questions based upon overloading and overriding. 

So, if you want to do well on Java Interviews as well as want to write good, powerful, and flexible code using object-oriented programming techniques, spare some time to understand overloading and overriding in Java. It will help you to leverage Polymorphism better.


If you are interested in some more Java interview questions based upon different topics then you can also see the following lists, which includes questions from multi-threading, collection framework, JDBC, frameworks, design patterns, web services, and several other topics :
  • Top 20 ArrayList based Java Interview Questions and Answers [article]
  • 40 Core Java Questions from Phone Interviews [list]
  • 15 Java Enum Interview Questions with Answers and Explanations [questions]
  • 18 Java Interview Questions based upon GOF Design Patterns and OOP [questions]
  • Top 21 Frequently asked Java interview questions for freshers [article]
  • 12 Java Multithreading and Concurrency based Interview Questions [see here]
  • JDBC Interview Questions and Answers for 2 to 4 years experienced developers [see here]
  • 10 Spring Framework-based Interview Questions [article]
  • 10 Must know Java Collection framework Interview Questions and Answers [read here]
  • 10 Java Web Services based Questions [list]
  • Top 10 Advanced Java Questions for Experienced and Senior Programmers [see here]
  • 22 Array concepts-based Interview Questions in Java? [answers]

Thanks for reading this article so far. If you like an object-oriented programming tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

And lastly one question for you? What is SOLID principle? Can you name all the 5 object oriented principle which are part of SOLID? 

4 comments:

  1. The concept of method overloading and overriding is very important for Java developers. I often see one or two question from these topics in Java Phone interviews, it is also important for OCAJP and OCPJP point of view, especially to solve the code based problems.

    ReplyDelete
  2. Just got a new question to add in this list, Thanks to Regu S.

    How to call the overridden method of superclass in Java?
    Well, you can call it by using super keyword e.g. super.count() will call the count() method of super class even if it is overridden in subclass.

    ReplyDelete
    Replies
    1. You can't. You can't choose which implementation to execute i.e the parent's or the subclass' while invoking the method from the subclass' object, but you can call the superclass method from within the subclass using the 'super' keyword

      Delete
    2. That's what I say, isn't it? but thanks for adding clarity that you can only use this code form subclass, but mentioning super implicitly imply that.

      Delete

Feel free to comment, ask questions if you have any doubt.