Code Pumpkin

Java Method Overriding Interview Questions

December 17, 2017
Posted by Abhi Andhariya

In our previous article, we have discussed tricky programming questions based on method overloading. However, Method overriding programming questions are more interesting and requires depth understanding of the concept than that of method overloading. Before moving to programming questions, lets understand the basic concepts of method overriding.

Method Overriding

Using method overriding, child class can provide its own implementation of the method which is already present in the parent class or declared in parent interface.

In other words, when method in the sub class has the same name, same parameters and same return type (or co-variant return type) as parent class or interface, then we can say that child class method has overridden the parent class method.

For Example, 

Lets understand this using simple example.

Method Overriding Programming Interview Questions

We have two classes : parent class Shape and child class Circle which extends Shape class.

Both the class has common method draw(). Circle class has provided its own implementation of draw() method. In other words, it has overridden draw() method of Shape class.

Along with draw() method, Shape class also contains fill() method which has not been overridden by Circle class. But this method will be inherited to Circle class with default implementation.

Purpose of method overriding is very clear here. Circle class wants to provide its own implementation of draw() method so that when it calls this method, it will print 'Circle' instead of 'Shape'.


public class PumpkinDemo {

	public static void main(String[] args) {
		Shape s = new Circle();

		s.draw();
        s.fill();
	}
}

class Shape{
	public void draw()
	{
		System.out.println("Shape");
	}
	
	public void fill()
	{
		System.out.println("Shape Filled with color");
	}

}

class Circle extends Shape{
	public void draw()
	{
		System.out.println("Circle");
	}
}

class Square extends Shape{
    public void draw()
    {
        System.out.println("Square");
    }
}

class Hexagon extends Shape{
    public void draw()
    {
        System.out.println("Hexagon");
    }
}

output


Circle
Shape Filled with color

Why is it known as Runtime polymorphism?

In above example, we have created reference of type Shape, but object of type Circle. When we call method draw(), jvm decides method of which class needs to be called at runtime. 

In short, if we create a object of child class and if child class has overridden the method, then child class method will be called e.g. draw(). If method has not been overridden in the child class, then parent class method will be called e.g. fill().

You can also refer our article on method overloading to know more about Compile-Time Polymorphism or static binding.


Programming Interview Questions

We have divided the questions into six categories so that it would be easier for you to understand the concepts.

  1. Access Modifiers
  2. static methods
  3. Member Variables
  4. Exception Handling
  5. Return types
  6. Method Parameters

We have listed down all such questions and their answers with explanation. But we suggest you guys to first try solving and guessing the answer of each question and then read its answer. 


Access Modifiers

Question 1) What would be the output of below code?


public class PumpkinDemo {

	public static void main(String[] args) {
		Shape s = new Circle();
		s.draw();
	}
}

class Shape{
	protected void draw()
	{
		System.out.println("Shape");
	}
}

class Circle extends Shape{
	public void draw()
	{
		System.out.println("Circle");
	}
}

Here method in parent class has protected scope, but in child class it is public. Will method overriding work here? Will it print Shape or Circle?

Answer: Method overriding has nothing to do with access modifier scopes. It will print Circle in above code. 


Question 2) As a follow up question, interviewer may ask you : What will happen if I change scope of draw() method from protected to private in Shape class?

Answer : It will give you a compile time error in main() method where you are calling s.draw() as we can not call the private method from outside the class.


Question 3) What would be the output of below code?


public class PumpkinDemo {

	public static void main(String[] args) {
		Shape s = new Circle();
		s.draw();
	}
}

class Shape{
	public void draw()
	{
		System.out.println("Shape");
	}
}

class Circle extends Shape{
	private void draw()
	{
		System.out.println("Circle");
	}
}

Answer:

Above code will give you compile time error as we cannot reduce the visibility or scope of the inherited method from parent class i.e. public void draw() to private void draw().


Static methods

Question 4) This question is not related to inheritance or method overriding, but it is one of our favorite question. Many programmer gives confused look when we ask them this one. Have a look at below code and guess the output.


public class PumpkinDemo {

	public static void main(String[] args) {
		Shape s = null;
		s.draw();
	}
}

class Shape{
	public static void draw()
	{
		System.out.println("Shape");
	}
}

Will above code give NullPointerException? Or it will print Shape as output?

Answer : It won't give NullPointerException as draw() is a static method and compiler will replace reference variable with class name i.e. Shape.draw()


Question 5) What would be the output of below code?


public class PumpkinDemo {

	public static void main(String[] args) {
		Shape s = new Circle();
		s.draw();
	}
}

class Shape{
	public static void draw()
	{
		System.out.println("Shape");
	}
}

class Circle extends Shape{
	public static void draw()
	{
		System.out.println("Circle");
	}
}

Answer: 

It will print Shape as output. Method overriding happens only with instance methods. Static methods are attached to class and compiler converts reference variable to class name i.g. Shape.draw() 


Question 6) What will happen if we will remove static keyword from the draw() method of Circle class. Shape class still contains the public static void draw() method.

Answer: It will give compile-time time error saying 'This instance method cannot override the static method from Shape'.


Member Variables

Question 7) Guess the output of below code


public class PumpkinDemo {

	public static void main(String[] args) {
		Shape s = new Circle();
		System.out.println(s.name);
	}
}

class Shape{
	String name = "Shape";
}

class Circle extends Shape{
	String name = "Circle";
}

Output:


Shape

Answer : Member variables cannot be overridden. In other words, Variables are resolved at compile-time and methods at run-time.


Exception Handling

Question 8) Can overridden method throw different exception than the one being thrown in parent class method. For Example, Will below code compile successfully?


import java.io.FileNotFoundException;
import java.io.IOException;

public class PumpkinDemo {

	public static void main(String[] args) throws IOException{
		Shape s = new Circle();
		s.draw();
	}
}

class Shape{
	public void draw() throws IOException
	{
		System.out.println("Shape");
	}
}

class Circle extends Shape{
	public void draw() throws FileNotFoundException 
	{
		System.out.println("Circle");
	}
}

Answer:

While overriding a method, you can compress the scope of checked exception but you cannot widen it. Also you can not throw any other checked exception which is not being thrown in parent class method.

Here, FileNotFoundException is a child class of IOException. So, above code will compile successfully and it will give Circle as output.

If we change FileNotFoundException to generic Exception in above code, then it will give compile time error saying 'Exception Exception is not compatible with throws clause in Shape.draw()'.


Question 9) Will below code compile successfully?


public class PumpkinDemo {

	public static void main(String[] args){
		Shape s = new Circle();
		s.draw();
	}
}

class Shape{
	public void draw() throws ArithmeticException
	{
		System.out.println("Shape");
	}
}

class Circle extends Shape{
	public void draw() throws RuntimeException 
	{
		System.out.println("Circle");
	}
}

Answer: Yes. Overridden methods can throw any RuntimeException irrespective of its scope unlike checked exception.


Return Type

Question 10) Can a return type be different in overridden method? Guess the output of below code.


public class PumpkinDemo {

	public static void main(String[] args){
		Parent p = new Child();
		p.testMethod();
	}
}

class Parent{
	public Number testMethod()
	{
		System.out.println("Parent");
		return 0;
	}
}

class Child extends Parent{
	public Integer testMethod() 
	{
		System.out.println("Child");
		return 0;
	}
}

Answer: Above code will compile successfully and prints Child as output. So is different return type allowed in method overriding?

Well Number is a parent class of Integer Wrapper class, and that is why above code compiled successfully. They are called covariant return types. You can check Wrapper classes Hierarchy in below image.

Wrapper Classes Hierarchy - Method Overridding

The covariant return types are newly introduced since Java 5.0, and used during method overridingCovariant return type allows us to change the return type of the overriding method in the subclass; however this return type in subclass method must be a subtype of super class method return type

Below two combinations will give you compile time errors:

1) Parent class method return type : Integer
     Child class method return type : Number or Long

2) Parent class method return type : String
     Child class method return type : Number or Long


Method Parameters

Question 11) Here are the last two questions of this article. Guess the output of below code:


public class PumpkinDemo {

	public static void main(String[] args){
		Parent p = new Child();
		p.testMethod(0);
	}
}

class Parent{
	public void testMethod(Number n)
	{
		System.out.println("Parent");
	}
}

class Child extends Parent{
	public void testMethod(Integer n) 
	{
		System.out.println("Child");
	}
}

Confused? Does java allows covariant method parameters? Is this method overriding?

Answer: 

Well, compiler will consider both of above methods as different methods and it is not method overriding. Above program will give priority to Parent class testMethod() and prints Parent as output. 


Question 12) What will be the output if we change main() method as below 


public static void main(String[] args){
	Child p = new Child();
	p.testMethod(0);
}

Output:


Child

Interesting, isn't it?

That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.

Happy Learning 🙂

If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.

We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.



About the Author


Surviving Java Developer, Passionate Blogger, Table Tennis Lover, Bookworm, Occasional illustrator and a big fan of Joey Tribbiani, The Walking Dead and Game of Thrones...!!



Tags: , , , , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.
Total Posts : 124
follow us in feedly

Like Us On Facebook