Draw a Circle Programming Question

In our previous article, we take discussed catchy programming questions based on method overloading. All the same, Method overriding programming questions are more interesting and requires depth agreement of the concept than that of method overloading. Before moving to programming questions, lets sympathise the basic concepts of method overriding.

Method Overriding

Using method overriding, child form tin 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 grade has the aforementioned name, same parameters and same render blazon (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 empathize this using unproblematic example.

Method Overriding Programming Interview Questions

Nosotros accept two classes : parent grade Shape and child class Circle which extends Shape class.

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

Forth with depict() method, Shape grade besides contains fill() method which has not been overridden past Circumvolve form. But this method will exist inherited to Circle form with default implementation.

Purpose of method overriding is very clear here. Circumvolve form wants to provide its ain implementation of draw() method and then that when it calls this method, information technology will print 'Circle' instead of 'Shape'.

            public grade PumpkinDemo {  	public static void main(String[] args) { 		Shape south = new Circle();  		south.draw();         southward.make full(); 	} }  grade Shape{ 	public void draw() 	{ 		System.out.println("Shape"); 	} 	 	public void fill() 	{ 		Arrangement.out.println("Shape Filled with colour"); 	}  }  class Circle extends Shape{ 	public void draw() 	{ 		Organisation.out.println("Circle"); 	} }  class Square extends Shape{     public void draw()     {         Organization.out.println("Square");     } }  class Hexagon extends Shape{     public void draw()     {         System.out.println("Hexagon");     } }

output

            Circle Shape Filled with color

Why is information technology known every bit Runtime polymorphism?

In in a higher place case, nosotros have created reference of type Shape, simply object of type Circle. When we call method describe(), jvm decides method of which class needs to exist chosen at runtime.

In short, if nosotros create a object of kid class and if child class has overridden the method, then kid class method will be called east.g. describe(). If method has not been overridden in the child form, then parent class method volition be chosen eastward.g. fill up().

You tin can too refer our article on method overloading to know more than most Compile-Fourth dimension Polymorphism or static binding.


Programming Interview Questions

Nosotros have divided the questions into 6 categories so that it would exist easier for yous to understand the concepts.

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

Nosotros have listed down all such questions and their answers with caption. Only we suggest you guys to starting time try solving and guessing the respond of each question and so read its reply.


Admission Modifiers

Question ane) What would exist the output of below lawmaking?

            public class PumpkinDemo {  	public static void principal(String[] args) { 		Shape southward = new Circle(); 		due south.depict(); 	} }  class Shape{ 	protected void draw() 	{ 		System.out.println("Shape"); 	} }  class Circle extends Shape{ 	public void describe() 	{ 		System.out.println("Circle"); 	} }

Here method in parent class has protected scope, just in child class it is public. Volition method overriding work here? Will information technology impressShape or Circumvolve?

Respond:Method overriding has nothing to exercise with access modifier scopes. It will print Circle in higher up lawmaking.


Question 2)Equally a follow upwardly question, interviewer may inquire you : What volition happen if I change scope of draw() method from protected to private in Shape class?

Answer :It will requite yous a compile time error in chief() method where you are calling s.draw() as we tin can not phone call the private method from outside the course.


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

            public grade PumpkinDemo {  	public static void main(String[] args) { 		Shape s = new Circumvolve(); 		s.draw(); 	} }  class Shape{ 	public void draw() 	{ 		Organisation.out.println("Shape"); 	} }  class Circle extends Shape{ 	individual void draw() 	{ 		Organization.out.println("Circle"); 	} }

Answer:

In a higher place code will give y'all compile time error every bit we cannot reduce the visibility or scope of the inherited method from parent class i.due east. public void draw() to private void draw().


Static methods

Question 4)This question is not related to inheritance or method overriding, simply it is i of our favorite question. Many programmer gives dislocated look when nosotros ask them this one. Accept a look at below lawmaking and guess the output.

            public class PumpkinDemo {  	public static void main(String[] args) { 		Shape s = nada; 		due south.depict(); 	} }  class Shape{ 	public static void draw() 	{ 		System.out.println("Shape"); 	} }

Will above code give NullPointerException? Or it will printShape as output?

Answer :It won't give NullPointerException as draw() is a static method and compiler volition supplant reference variable with form proper name i.e. Shape.describe()


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

            public class PumpkinDemo {  	public static void principal(String[] args) { 		Shape due south = new Circle(); 		s.draw(); 	} }  grade Shape{ 	public static void draw() 	{ 		Arrangement.out.println("Shape"); 	} }  class Circumvolve extends Shape{ 	public static void draw() 	{ 		Arrangement.out.println("Circle"); 	} }

Reply:

It will printShape as output. Method overriding happens just with case methods. Static methods are attached to grade and compiler converts reference variable to class name i.grand. Shape.draw()


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

Answer:Information technology volition give compile-fourth dimension time fault maxim 'This instance method cannot override the static method from Shape'.


Fellow member Variables

Question vii)Estimate the output of beneath code

            public class PumpkinDemo {  	public static void primary(String[] args) { 		Shape s = new Circle(); 		System.out.println(due south.name); 	} }  class Shape{ 	String proper noun = "Shape"; }  class Circumvolve extends Shape{ 	String proper 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 form method. For Example, Will below code compile successfully?

            import java.io.FileNotFoundException; import coffee.io.IOException;  public class PumpkinDemo {  	public static void main(Cord[] args) throws IOException{ 		Shape south = new Circle(); 		s.draw(); 	} }  class Shape{ 	public void draw() throws IOException 	{ 		Arrangement.out.println("Shape"); 	} }  course Circumvolve extends Shape{ 	public void draw() throws FileNotFoundException  	{ 		System.out.println("Circle"); 	} }

Answer:

While overriding a method, you tin shrink the scope of checked exception but y'all cannot widen it. Also you can not throw any other checked exception which is non being thrown in parent grade method.

Hither,FileNotFoundExceptionis a kid class ofIOException. So, above code will compile successfully and information technology will requiteCircumvolveas output.

If we modifyFileNotFoundException to generic Exception in to a higher place lawmaking, then it volition requite compile fourth dimension error maxim 'Exception Exception is not compatible with throws clause in Shape.describe()'.


Question nine)Will below lawmaking compile successfully?

            public grade PumpkinDemo {  	public static void main(String[] args){ 		Shape due south = new Circle(); 		s.draw(); 	} }  class Shape{ 	public void draw() throws ArithmeticException 	{ 		System.out.println("Shape"); 	} }  class Circle extends Shape{ 	public void describe() throws RuntimeException  	{ 		System.out.println("Circle"); 	} }

Reply:Yes. Overridden methods can throw whatsoever RuntimeException irrespective of its scope dissimilar checked exception.


Return Type

Question 10)Can a return type be unlike in overridden method? Approximate the output of beneath code.

            public class PumpkinDemo {  	public static void chief(String[] args){ 		Parent p = new Kid(); 		p.testMethod(); 	} }  class Parent{ 	public Number testMethod() 	{ 		Arrangement.out.println("Parent"); 		return 0; 	} }  form Child extends Parent{ 	public Integer testMethod()  	{ 		System.out.println("Child"); 		return 0; 	} }

Respond:In a higher place lawmaking will compile successfully and printsChildas output. And then is unlike 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 epitome.

Wrapper Classes Hierarchy - Method Overridding

Thecovariant render types are newly introduced since Coffee 5.0, and used duringmethod overriding.Covariant render type allows us to change thereturn type of theoverriding method in the subclass; however thisreturn type in bracketmethod must be a subtype of super classmethod return type.

Below two combinations volition give you compile fourth dimension errors:

1) Parent class method render type : Integer,
Child course method render type : Number or Long

2) Parent course method return blazon : String,
Child grade method return type : Number or Long


Method Parameters

Question 11)Here are the last 2 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 Kid 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 equally dissimilar methods and it is non method overriding. In a higher place program will requite priority to Parent class testMethod() and prints Parent as output.


Question 12)What will be the output if we modify main() method equally beneath

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

Output:

            Kid

Interesting, isn't it?

clementbese1996.blogspot.com

Source: https://codepumpkin.com/method-overriding-interview-questions/

0 Response to "Draw a Circle Programming Question"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel