Session 5 - Inheritance, Interfaces, Polymorphism
Session 5 - Inheritance, Interfaces, Polymorphism
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.
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.
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.
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.
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) 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.
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.
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
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.
For example:
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.
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.
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.
Output :
Inside try block
Q4. What are the differences between Error and Exception in java?
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.
import java.util.*;
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.
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.
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.
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.
Syntax:
throw InstanceOfThrowableType;
For example:
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 :
Output :
Rethrowing the caught exception below
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.
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.
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.
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.
printStackTrace() function is used to print the detailed information about the exception thrown by the
try/catch block.
• getMessage()
• Throwable getCause()
• toString()
• printStackTrace()
• StackTraceElement [] getStackTrace()
ArrayIndexOutOfBoundsException arises while trying to access an index of the array that does not
exist or out of the bound of this array.
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.
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.
a. printStackTrace()
b. toString()
c. getMessage()
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.