0% found this document useful (0 votes)
29 views

Session 5 - Inheritance, Interfaces, Polymorphism

Oops concept

Uploaded by

Shivang Maurya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Session 5 - Inheritance, Interfaces, Polymorphism

Oops concept

Uploaded by

Shivang Maurya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Session 5 - Inheritance, Polymorphism, Interfaces

Inheritance
1. What is Inheritance in Java?
Ans: The technique of creating a new class by using an existing class functionality is called
inheritance in Java. In other words, inheritance is a process where a child class acquires all the
properties and behaviors of the parent class.
2. Why do we need to use inheritance?
Or, what is the purpose of using inheritance?
Ans: Inheritance is one of the main pillars of OOPs concept. Some objects share certain properties and
behaviors. By using inheritance, a child class acquires all properties and behaviors of parent class.
There are the following reasons to use inheritance in java.
▪ We can reuse the code from the base class.
▪ Using inheritance, we can increase features of class or method by overriding.
▪ Inheritance is used to use the existing features of class.
▪ It is used to achieve runtime polymorphism i.e method overriding.

3. What is Is-A relationship in Java?


Ans: Is-A relationship represents Inheritance. It is implemented using the “extends” keyword. It is
used for code reusability.
4. What is super class and subclass?
Ans: A class from where a subclass inherits features is called superclass. It is also called base class or
parent class.
A class that inherits all the members (fields, method, and nested classes) from other class is called
subclass. It is also called a derived class, child class, or extended class.
5. How is Inheritance implemented/achieved in Java?
Ans: Inheritance can be implemented or achieved by using two keywords:
1. extends: extends is a keyword that is used for developing the inheritance between
two classes and two interfaces.
2. implements: implements keyword is used for developing the inheritance between a
class and interface.
6. Write the syntax for creating the subclass of a class?

Ans: A subclass can be created by using the “extends” keyword. The syntax for declaring a subclass
of class is as follows:
class subclassName extends superclassName
{
// Variables of subclass
// Methods of subclass
}
where class and extends are two keywords.
7. Which class in Java is superclass of every other class?
Ans: In Java, Object class is the superclass of every other class.
8. How will you prove that the features of Superclass are inherited in Subclass?
Ans: Refer to this tutorial: Inheritance in Java with Realtime Example
9. Can a class extend itself?
Ans: No, a class cannot extend itself.
10. Can we assign superclass to subclass?
Ans: No.
11. Can a class extend more than one class?
Ans: No, one class can extend only a single class.
12. Are constructor and instance initialization block inherited to subclass?
Ans: No, constructor and instance initialization block of the superclass cannot be inherited to its
subclass but they are executed while creating an object of the subclass.
13. Are static members inherited to subclass in Java?
Ans: Static block cannot be inherited to its subclass.
A static method of superclass is inherited to the subclass as a static member and non-static method is
inherited as a non-static member only.
14. Can we extend (inherit) final class?
Ans: No, a class declared with final keyword cannot be inherited.
15. Can a final method be overridden?
Ans: No, a final method cannot be overridden.
16. Can we inherit private members of base class to its subclass?
Ans: No.
17. What is order of calling constructors in case of inheritance?
Ans: In case of inheritance, constructors are called from the top to down hierarchy.
18. Which keyword do you use to define a subclass?
Or, which keyword is used to inherit a class?
Ans: extends keyword.
19. What are the advantages of inheritance in Java?
Ans: The advantages of inheritance in java are as follows:
▪ We can minimize the length of duplicate code in an application by putting the
common code in the superclass and sharing it amongst several subclasses.
▪ Due to reducing the length of code, the redundancy of the application is also reduced.
▪ Inheritance can also make application code more flexible to change.

20. What are the types of inheritance in Java?


Ans: The various types of inheritance are as follows:
a. Single inheritance
b. Multi-level inheritance
c. Hierarchical inheritance
d. Multiple inheritance
e. Hybrid inheritance
21. What are the various forms of inheritance available in Java?
Ans: The various forms of inheritance to use are single inheritance, hierarchical inheritance, and
multilevel inheritance.
22. What is single inheritance and multi-level inheritance?
Ans: When one class is extended by only one class, it is called single level inheritance. In single-level
inheritance, we have just one base class and one derived class.
A class which is extended by a class and that class is extended by another class forming chain
inheritance is called multilevel inheritance.
23. What is Multiple inheritance in Java?
Ans: A class that has many superclasses is known as multiple inheritance. In other words, when a
class extends multiple classes, it is known as multiple inheritance.
24. Why multiple inheritance is not supported in java through class?
Ans:
Multiple inheritance means that one class extends two superclasses or base classes but in Java, one
class cannot extend more than one class simultaneously. At most, one class can extend only one class.
Therefore, to reduce ambiguity, complexity, and confusion, Java does not support multiple inheritance
through classes.
For more detail, go to this tutorial: Types of Inheritance in Java
25. How does Multiple inheritance implement in Java?
Ans: Multiple inheritance can be implemented in Java by using interfaces. A class cannot extend more
than one class but a class can implement more than one interface.
26. What is Hybrid inheritance in java? How will you achieve it?
Ans: A hybrid inheritance in java is a combination of single and multiple inheritance. It can be
achieved through interfaces.
27. How will you restrict a member of a class from inheriting its subclass?
Ans: We can restrict members of a class by declaring them private because the private members of
superclass are not available to the subclass directly. They are only available in their own class.
28. Can we access subclass members if we create an object of superclass?
Ans: No, we can access only superclass members but not the subclass members.
29. Can we access both superclass and subclass members if we create an object of subclass?
Ans: Yes, we can access both superclass and subclass members.
30. What happens if both superclass and subclass have a field with the same name?
Ans: Only subclass members are accessible if an object of subclass is instantiated.
31. Will the code successfully compiled? If yes, what is the output?
public class A {
int x = 20;
}
public class B extends A {
int x = 30;
}
public class Test {
public static void main(String[] args)
{
B b = new B();
System.out.println(b.x);

A a = new A();
System.out.println(a.x);

A a2 = new B();
System.out.println(a2.x);
}
}
Ans: Yes, code will be successfully compiled. The output is 30, 20, 20.

32. Which of the following is correct way of inheriting class A by class B?


a) class B + class A { }
b) class B inherits class A { }
c) class B extends A { }
d) class B extends class A { }
Ans: c
33. Is interface inherited from the Object class?
Ans: No.
34. What is the output of executing code of class Test?
public class A {
void m1() {
System.out.println("m1 in class A");
}
}
public class B extends A {
void m1() {
System.out.println("m1 in class B");
}
}
public class Test {
public static void main(String[] args)
{
B b = new B();
b.m1();

A a = new A();
a.m1();

A a2 = new B();
a2.m1();
}
}
Ans: The result is m1 in class B, m1 in class A, m1 in class B.
Interface
1. What is an interface in Java?
Ans: An interface in Java is a mechanism that is used to achieve complete abstraction. It is basically a
kind of class that contains only constants and abstract methods.
2. Can we define private and protected modifiers for data members (fields) in interfaces?
Ans: No, we cannot define private and protected modifiers for variables in interface because the fields
(data members) declared in an interface are by default public, static, and final.
3. Which modifiers are allowed for methods in an Interface?
Ans: Only abstract and public modifiers are allowed for methods in interfaces.
4. Suppose A is an interface. Can we create an object using new A()?
Ans: No, we cannot create an object of interface using new operator. But we can create a reference of
interface type and interface reference refers to objects of its implementation classes.
5. Can we define an interface with a static modifier?
Ans: Yes, from Java 8 onwards, we can define static and default methods in an interface. Prior to Java
8, it was not allowed.
6. Suppose A is an interface. Can we declare a reference variable a with type A like this: A a;
Ans: Yes.
7. Can an interface extends another interface in Java?
Ans: Yes, an interface can extend another interface.
8. Can an interface implement another interface?
Ans: No, an interface cannot implement another interface.
9. Is it possible to define a class inside an interface?
Ans: Yes, we can define a class inside an interface.

10. Which of the following is a correct representation of interface?


a) public abstract interface A {
abstract void m1() {};
}
b) public abstract interface A {
void m1();
}
c) abstract interface A extends B, C {
void m1();
}
d) abstract interface A extends B, C {
void m1(){};
}
e) abstract interface A {
m1();
}
f) interface A {
void m1();
}
g) interface A {
int m1();
}
h) public interface A {
void m1();
}
public class B implements A {
}
i) public interface A {
void m1();
}
Public interface B {
void m1();
}
public interface C extends A, B {
void m1();
}
Ans: b, c, f, g, i.
11. Identify the error in the following code.
a)
interface A {
void m1();
}
public class B implements A {
void m1(){
System.out.println("One");
}
}
Ans: We cannot reduce the visibility of inherited method from interface A.
12. What will be the output of the following program?
interface A {
int x = 10;
void m1();
}
public class B implements A {
int x = 20;
public void m1(){
System.out.println("One");
}
}
public class Test {
public static void main(String[] args){
A a = new B();
a.m1();
System.out.println(a.x);
}
}
Ans: Output: One, 10.
13. Can an interface extend multiple interfaces?
Ans: Yes, an interface can extend multiple interfaces.
14. Can an interface has instance and static blocks?
Ans: No.
15. What will be the output of the following program?
interface A {
int x = 10;
}
interface B {
int x = 20;
}
interface C extends A, B{
int x = 30;
public static void main(String[] args){
int a = A.x;
int b = B.x;
int c = C.x;

System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Ans: Output: 10, 20, 30
16. What happens if a class has implemented an interface but has not provided implementation
for that method defined in Interface?
Ans: The class has to be declared with an abstract modifier. This will be enforced by the Java
compiler.
17. Why an Interface method cannot be declared as final in Java?
Or, Can a method within an interface be marked as final?
Ans: Not possible. Doing so will result the compilation error problem. This is because a final method
cannot be overridden in java. But an interface method should be implemented by another class.
So, the interface method cannot be declared as final. The modifiers such as public and abstract are
only applicable for method declaration in an interface.
18. Can an interface be final?
Ans: No. Doing so will result compilation error problem.
19. Why an interface cannot have a constructor?
Ans: Inside an interface, a constructor cannot be called using super keyword with hierarchy.
20. Why an Interface can extend more than one Interface but a Class can’t extend more than
one Class?
Ans: We know that Java doesn’t allow multiple inheritance because a class extends only one class.
But an Interface is a pure abstraction model. It does not have inheritance hierarchy like classes.
Therefore, an interface allows to extend more than one Interface.
21. What is the use of interface in Java?
Or, why do we use an interface in Java?
Ans: There are many reasons to use interface in java. They are as follows:
a. An interface is used to achieve fully abstraction.
b. Using interfaces is the best way to expose our project’s API to some other project.
c. Programmers use interface to customize features of software differently for different objects.
d. By using interface, we can achieve the functionality of multiple inheritance.
22. Is it necessary to implement all abstract methods of an interface?
Ans: Yes, all the abstract methods defined in interface must be implemented.
23. Can we define a variable in an interface? What type it should be?
Ans: Yes, we can define variable in an interface that must be implicitly static and final.
24. Can we re-assign a value to a variable of interface?
Ans: No, variables defined inside the interface are static and final by default. They are just like
constants. We can’t change their value once they got.
25. What is the difference between abstract class and interface in Java?
Ans: Refer to this tutorial: 12 Difference between Abstract class and Interface in Java
26. What is the difference between class and interface in Java?
Ans: Refer to this tutorial: Difference between Class and Interface in Java
27. What is a Marker Interface in Java?
Ans: An Interface that doesn’t have any data members or methods is called marker interface in java.
For example, Serializable, Cloneable, Remote, etc.
28. What is a Nested interface?
Ans: An interface declared inside another interface is called nested interface. By default, it is static in
nature. It is also known as static interface.
29. Can we reduce the visibility of interface method while overriding?
Ans: No, while overriding any interface methods, we must use public only. This is because all
interface methods are public by default. We cannot reduce the visibility while overriding them.
30. Can we define an interface inside a method as local member?
Ans: No, we can’t define an interface as local member of a method like local inner class.
Polymorphism

(1) What is polymorphism in java?


In java, Polymorphism means "one name many forms". In other words, you can say whenever an
object producing different-different behavior in different-different circumstances is called
polymorphism in java.

(2) Give real-life examples of polymorphism


Let's understand real-time example of polymorphism.

1) Related to person
• Suppose you are in the classroom that time you will behave like a student.
• Suppose when you at home you behave like son or daughter.
• Suppose you are in the market at that time you behave like a customer.

2) Related to product

Let's take an example of an Air conditioner which produces hot air in winter and cold air in summer.

So there is one name but it producing different - different output according to the situation.

(3) How many types are of polymorphism in java?


There are two types of polymorphism in java and these are given below.
• Compile-Time polymorphism or Static polymorphism.
• Run-time polymorphism or Dynamic polymorphism.

(4) Can we achieve polymorphism through data member?


No, Polymorphism is always achieved via behavior of an object only properties of an object do not
play any role in case of polymorphism.

(5) What are compile-time and run-time polymorphism?


Compile-Time Polymorphism
The best example of compile-time or static polymorphism is the method overloading. Whenever an
object is bound with their functionality at compile time is known as compile-time or static
polymorphism in java.

Run-Time Polymorphism

The best example of run-time or dynamic polymorphism is the method overriding. Whenever an
object is bound with their functionality at run-time is know as run-time or dynamic polymorphism in
java.

(6) What is method overloading?


Whenever we have more than one same name method but a different number of arguments or
different data types in the same class is known as method overloading in java. Method overloading the
example of compile-time polymorphism.

For example:

class Addition
{
void add(int a, int b)//with 2 arguments
{
System.out.println(a+b);
}
void add(int a, int b, int c)//change no of arguments i.e 3
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Addition a = new Addition();
a.add(10,20);
a.add(20,5,6);
}
}
Output: 30
31

(7) What is method overriding?


In java, whenever we have same name method in parent and child class with the same number of
arguments and same data types is known as method overriding in java. Method overriding is the
example of dynamic polymorphism.

For example:

class Parent
{
void show()
{
System.out.println("Parent");
}
}
class Child extends Parent
{
void show()
{
System.out.println("Child");
}
public static void main(String args[])
{
Parent p =new Child();
p.show();
}
}

Output: Child
(8) How to achieve static polymorphism?
Compile - time polymorphism is also known as static polymorphism. We can achieve static
polymorphism through method overloading in java.

(9) How to achieve dynamic polymorphism?


Run-time polymorphism is also known as dynamic polymorphism. We can achieve dynamic
polymorphism through method overriding.

(10) Difference between method overloading and method overriding?


Click on this link to see the differences between method overloading and method overriding in java.

(11) What is up-casting in java?


Whenever we put the reference id of a child class object into the parent class reference variable is
known as upcasting in java.

For example:

Parent p = new Child();//upcasting declaration

(12) What is static binding?


Static binding is also known as compile - time polymorphism. Method overloading is the example of
static binding.

In static binding, The type of object is determined at compile-time.

Static binding is also known as early binding.

(13) What is dynamic binding?


Dynamic binding is also known as run-time polymorphism. Method overriding is the example of
dynamic binding.

In dynamic binding, The type of object is determined at run-time.

Dynamic binding is also known as late binding.


(14) Can we achieve method overloading by changing the return type?
No, We cannot achieve method overloading through return type in java.

(15) What is runtime polymorphism?


Runtime polymorphism is also known as method overriding and it is achieved at run-time.
Exception Handling
Q1. What is an Exception in java?

An Exception is a failure condition that occurs during the execution of a program and disrupts the
normal flow of the program. It has to be handled properly, failing which program will be terminated
abruptly.

Q2. How the exceptions are handled in java?

Exceptions handling can be done using try, catch and finally blocks.

try : The code or set of statements that may raise exception should be try block.
catch : This block catches the exceptions thrown in the try block.
finally : This block of code is always executed whether an exception has occurred in the try block or
not except in one scenario explained in below question.

Q3 Is finally block always get executed in the java program?

This question is very important. finally block is always executed but there is one scenario when
finally block does not execute.
By using System.exit(0) in the try or catch block, results in finally block does not execute. The
reason is System.exit(0) line terminates the running java virtual machine. Termination leads to no
more execution of the program.

This is the only scenario when finally block fails to execute.

public class JavaHungry{


public static void main(String[] args)
{
try
{
System.out.println("Inside try block ");
/* After executing below line
jvm terminates the program */
System.exit(0);
}
catch (Exception e)
{
System.out.println("Inside catch block");
}
finally
{
System.out.println("Inside finally block");
}
}
}

Output :
Inside try block

Q4. What are the differences between Error and Exception in java?

Main differences between Error and Exception are :

a. Errors are caused by the JVM environment in which the application is running. Example:
OutOfMemoryError while Exceptions are caused by the application itself. Example:
NullPointerException.
b. Errors can only occur at runtime while Exceptions can occur at compile time or runtime.

You can find more differences between Error and Exception here.

Q5. What statements can exist in between try, catch and finally blocks?

No, try, catch and finally forms a single unit and no other statements should exist in between try,
catch and finally blocks.

Q6. Are we allowed to use only try block without a catch and finally blocks?

Prior to Java 7:
No, it is not allowed. If used it shows compilation error. The try block must be followed by a catch
block or finally block.

After Java 7 (Correct Answer):


Yes, it is possible to have a try block without a catch and finally blocks. The introduction of try-with-
resources concept makes it possible.
The only constraint is resources which we are passing as a parameter in try block must
implement AutoCloseable interface.

import java.util.*;

public class JavaHungry{


public static void main(String[] args)
{
/* After completion of try block,
the Scanner object would be auto closed
as Scanner class implements AutoCloseable
interface. */
try(Scanner sc = new Scanner(System.in))
{
System.out.println(" try without catch/finally block ");
}
}
}
Output :
try without catch/finally block

Q7. What are Checked and Unchecked exceptions in java?

Exceptions which are known to the compiler are called Checked exceptions. Checked exceptions are
checked at compile-time only.

Unchecked exceptions occur only at run time. Unchecked exceptions are also called as run time
exceptions. All subclasses of java.lang.RuntimeException and java.lang.Error is of Unchecked type.

Q8. What is the difference between Checked and Unchecked exceptions in java?

This is one of the most popular interview questions for java developers. Make sure this question is in
your to-do list before appearing for the interview.
Main differences between Checked and Unchecked exceptions are :

a. Checked exceptions are checked at compile time while Unchecked exceptions are checked at run
time.
b. Checked exceptions must be handled by try/catch block or throws keyword while Unchecked
exceptions are not necessary to handle.

find a detailed explanation here.

Q9. What is the difference between final, finally and finalize in java?

final keyword:
By declaring a variable as final, the value of final variable cannot be changed.
By declaring a method as final, method cannot be overridden.
By declaring a class as final, class cannot be extended.

finally:
Used after try or try-catch block, will get executed after the try and catch blocks without considering
whether an exception is thrown or not.

finalize:
Finalize method is the method that Garbage Collector always calls just before the deletion/destroying
the object which is no longer in use in the code.

Q10 What is try-with-resources concept in java? How it differs from an ordinary try statement?

According to Java docs, try-with-resources statement is a try statement that declares one or more
resources. It ensures that each resource is closed at the end of the statement.

try-with-resources statement can have catch or finally block similar to ordinary try statement. In a try-
with-resources statement, JVM makes sure catch or finally block is run after the resources declared
have been closed.

Q11. What is RuntimeException in java. Give example?

The exceptions which occur at runtime are called as RuntimeException. These exceptions are
unknown to the compiler. All subclasses of java.lang.RuntimeException are RuntimeExceptions.

For example:
NumberFormatException, NullPointerException, ClassCastException,
ArrayIndexOutOfBoundException etc.

Q12. What is the difference between ClassNotFoundException and NoClassDefFoundError in


java?

This question is important because very few Java developers are aware of the difference between
ClassNotFoundException and NoClassDefFoundError.

ClassNotFoundException:
An exception that occurs when you try to load a class at run time using Class.forName() or
loadClass() methods and mentioned classes are not found in the classpath is called
ClassNotFoundException.

NoClassDefFoundError:
An exception that occurs when a particular class is present at compile-time but was missing at run
time is called NoClassDefFoundError.

find a detailed explanation here.

Q13. Can we throw an exception manually/explicitly?

Yes, using throw keyword we can throw an exception manually.

Syntax:

throw InstanceOfThrowableType;

For example:

public class JavaHungry{


public static void main(String[] args)
{
try
{
// Creating an object of ArithmeticException
ArithmeticException ae = new ArithmeticException();
//Manually throwing ArithmeticException
throw ae;
}
catch (ArithmeticException e)
{
System.out.println("Caught the manually thrown Exception");
}
}
}

Output:
Caught the manually thrown Exception
Q14. Does catch block rethrow an exception in java?

Yes, catch block can rethrow an exception using throw keyword. It is called re-throwing an exception.

For example :

public class JavaHungry{


public static void main(String[] args)
{
try
{
// Creating an object of ArithmeticException
ArithmeticException ae = new ArithmeticException();
//Manually throwing ArithmeticException
throw ae;
}
catch (ArithmeticException e)
{
System.out.println("Rethrowing the caught exception below ");
//Rethrowing ArithmeticException
throw e;
}
}
}

Output :
Rethrowing the caught exception below

Exception in thread "main" java.lang.ArithmeticException


at JavaHungry.main(JavaHungry.java:7)

Q15. What is the use of throws keyword in java?

throws keyword is used to declare an exception. You can find a detailed explanation here.

Q16. Why it is always recommended that clean up activities like closing the DB connections and
I/O resources to keep inside a finally block?

finally block will always be executed except one scenario as discussed above in Q3. By ensuring the
cleanup operations in finally block, you will assure that those operations will be always executed
irrespective of whether an exception has occurred or not.

Q17. What is OutOfMemoryError in Exception Handling?

OutOfMemoryError is the subclass of java.lang.Error. It occurs when JVM runs out of memory.
Q18. What is ClassCastException in Exception Handling?

RunTimeException which occurs when JVM not able to cast an object of one type to another type is
called ClassCastException.

Q19. What is the difference between throws and throw in java?

This is one of the most frequently asked interview questions for java developers.
Main differences between throws and throw are :

a. throws keyword is used when writing methods, to declare that the method in question throws the
specified (checked) exception.
throw is used when an instruction is to explicitly throw the exception.
b. throws is used with a method signature while the throw is used inside a method.

You can find a detailed explanation of the difference between throw and throws in java here.

Q20. What is StackOverflowError in Exception Handling?

StackOverflowError is thrown by the JVM when stack overflows in a program.

Q21. Which class is the root class for all types of errors and exceptions in Exception Hierarchy?

java.lang.Throwable is the superclass for all types of errors and exceptions in java.

Q22. When do we use printStackTrace() method in java?

printStackTrace() function is used to print the detailed information about the exception thrown by the
try/catch block.

Q23. Give some examples of Checked exceptions?

SQLException, ClassNotFoundException, IOException

Q24. Give some examples of Unchecked exceptions?

ArrayIndexOutOfBoundsException, NullPointerException, NumberFormatException

Q25. List the Methods in the Throwable class?

Below are the important methods of Throwable class:

• getMessage()
• Throwable getCause()
• toString()
• printStackTrace()
• StackTraceElement [] getStackTrace()

Q26. What is a SQLException in Exception Handling?


An exception that provides information related to database access error or other errors is called SQL
Exception.

Q27. What is NumberFormatException in java?

NumberFormatException is thrown when you try to convert a String into a number.

Q28. What is ArrayIndexOutOfBoundsException in java?

ArrayIndexOutOfBoundsException arises while trying to access an index of the array that does not
exist or out of the bound of this array.

Q29. What will happen if an exception is thrown by the main method?

When an exception is thrown by the main method then JVM terminates the program. As a result, you
will find the exception message and stack trace in the system console.

Q30. Is it legal to have an empty catch block?

Yes, we can have an empty catch block in java but it is not the best practice. If an exception is caught
by the empty catch block, then we do not have any information about the exception occurred. You
should provide at least the logging statement to log the exception details.

Q31. What are the keywords in Java for Exception Handling?

throw, throws, try, catch and finally

Q32. List some important methods of Java Exception class?

a. printStackTrace()
b. toString()
c. getMessage()

Q33. What are the advantages of using Exceptions in your programs?

According to Java doc,

a. Separating "regular" code from error handling code.


b. The ability to propagate errors reporting up the call stack of methods.
c. Differentiating and grouping error types.

Written/Coding round Interview Questions:

Please go through the below link before attempting questions 46-50.

Q34-45 Programs on Exception Handling in Java with Answers.

Q46. What is unreachable catch block error?

When there is more than one catch block, then, the order of catch blocks must be from most specific
to most general ones. In other words, subclasses of Exception must come first and superclasses later.
If you try to keep superclasses first and subclasses later, the compiler will stop you and show
unreachable catch block error.

Q47. Can we provide the statements after finally block if the control is returning from the
finally block itself?

No, because control is returning from the finally block itself so it shows unreachable code error.

Q48. Does finally block get executed if either try or catch blocks are returning the control?

Yes, finally block will be always executed no matter whether try or catch blocks are returning the
control or not. There is one scenario where finally block does not execute, for more information check
out Q3.

Q49. Suppose there is a catch block corresponding to a try block with three statements –
statement1, statement2, and statement3. Assume that exception is thrown in statement2. Does
statement3 get executed?

Statement3 will not get executed because once a try block throws an exception, remaining statements
will not be executed.

Q50. What will happen if we override a superclass method which is throwing an unchecked
exception with a checked exception in the subclass?

If the overridden method throwing an unchecked exception, then the subclass overriding method must
have the same exception or any other unchecked exceptions. If you are trying to throw checked
exception with subclass overriding method then it will give a compilation error.

You might also like