Real-Time Encapsulation Interview Questions and Answers
Real-Time Encapsulation Interview Questions and Answers
In this tutorial, we will discuss Real-time Encapsulation Interview Questions and Answers with some
practical examples. We will try to present answers in very easy ways so that you could not get any trouble to
understand and remember the answers.
Ans: Encapsulation is a technique of making the fields private in the class and providing the access to the fields via
the public method.
If a field is declared private in the class then it cannot be accessed by anyone outside the class and hides the fields
within the class. Therefore, Encapsulation is also called data hiding.
Ans: Encapsulation means combining the data of our application and its manipulation in one place.
Encapsulation allows the state of an object to be accessed and modified through behavior. It reduces the coupling
of modules and increases the cohesion inside them.
➝ An encapsulated code is more flexible and easy to change with new requirements.
➝ Encapsulation prevents the other classes to access the private fields.
➝ Encapsulation allows modifying implemented code without breaking others code who have implemented the
code.
➝ It keeps the data and codes safe from external inheritance.
➝ If you don't define setter method in the class then the fields can be made read-only.
➝ If you don't define getter method in the class then the fields can be made write-only.
➝ Encapsulation also helps to write the immutable class in java which is the good choice in multithreading.
➝ The main benefit of encapsulation is the ability to modify the implemented code without breaking the others
code who have implemented the code.
➝ It also provides us with maintainability, flexibility, and extensibility to our code.
➝ A class can have total control over what is stored in its fields.
➝ Provide public setter and getter methods to modify the values of variables.
Example:
public class EncapsulationTest private String name; private String idNum; private int age; public int
getAge(){ return age; } public String getName(){ return name; } public String getIdNum(){ return idNum; }
public void setAge( int newAge){ age = newAge; } public void setName(String newName){ name = newName; }
public void setIdNum( String newId){ idNum = newId; } }
Ans: In Java, setter method is a method which is used for updating the values of a variable. This method is also
known as mutator method.
Getter method is a method which is used to retrieve the value of a variable or return the value of the private
member variable. This method is also known as an accessor method.
So for making your account safe, they declare balance variable as private so that anyone cannot see your
account balance and the person who have to see account balance then they will have to access private members
only through methods defined inside that class and this method will ask your account holder name or user Id, or
password for authentication.
Thus, security is achieved by utilizing the concept of data hiding. This is called Encapsulation.
10. How can the variable of the EncapsulationTest be accessed by using getter and setter methods?
Ans: The public setXXX() and getXXX() methods are access points of the instance variable of EncapsulationTest
class. Basically, these methods are known as getter and setter methods. Therefore, any class that wants to access
variable should access them through these getters and setters.
byte
short
int
long
char
boolean
float
double
Non primitive data types are called reference types in Java and they refer to an object. They are
created by the programmer and are not defined by Java like primitives are. A reference type
references a memory location where the data is stored rather than directly containing a value.
A primitive data type is one that fits the base architecture of the underlying computer such as int,
float, and pointer, and all of the variations, thereof such as char short long unsigned float double and
etc, are primitive data type.
Primitive data are only single values, they have not special capabilities.
The examples of Primitive data types are given byte, short, int, long, float, double, char etc.
The data type that are derived from primary data types are known as non-primitive data type.
The non-primitive data types are used to store the group of values.
There are the following differences between method overloading and method overriding in Java. They are as
follows:
1. Definition:
a. When a class has more than one method having the same name but different in parameters, it is called method
overloading in Java.
b. When the method of superclass is overridden in subclass to provide more specific implementation, it is
calledmethod overriding in Java.
2. Argument types:
a. Argument type must be different (at least order) in overloading.
b. In overriding, argument type must be the same (including order).
3. Method signature:
a. The signature of the overloaded method must be different.
b. The signature of the overriding method must be the same.
4. Return type:
a. In method overloading, the return type can be the same or different.
b. In method overriding, the return type must be the same until Java 1.4 version but Java 1.5 onwards, method
overriding can be done by changing the covariant return type.
5. Class:
a. Method overloading is generally performed in the same class.
b. Method overriding is performed in two classes through inheritance (Is-A relationship).
6. Private/static/final method:
a. Private, static, and final method can be overloaded in Java.
b. Overriding concept is not applicable to private, static, and final method. Private, static, and final method can be
overridden in Java.
7. Access modifiers:
a. In overloading, access modifiers can be anything or different.
b. In overriding, subclass method's access modifier must be same or higher than superclass method access
modifier i.e we cannot reduce the visibility subclass method while overriding.
8. Throws clause:
a. Exception thrown can be anything in the overloading concept.
b. In case of method overriding, if child class method throws any checked exception compulsory parent class
method should throw the same checked exception are its parent otherwise we will get compile time error but there is
no restriction for an unchecked exception.
9. Method resolution:
a. Method resolution in overloading always takes care by the compiler based on reference type.
b. Method resolution in overriding always takes care by JVM based on runtime object.
10. Polymorphism:
a. Method overloading is also known as compile-time polymorphism, static polymorphism, or early binding.
b. Method overriding is also known as runtime polymorphism, dynamic polymorphism, or late binding.
interface Test
{
default void show()
{
-----
-----
}
}
Lets see in the below example we have a OverloadExample class which has two static disp()methods
which differs in the number of parameters.
package com.javainterviewpoint;
package com.javainterviewpoint;
}
}
Running the above code will lead to the below exception
package com.javainterviewpoint;
import java.io.IOException;
class Parent
{
public static void display()
{
System.out.println("Welcome to Parent Class");
}
}
public class Child extends Parent
{
public static void display()
{
System.out.println("Welcome to Child class");
}
public static void main(String args[])
{
//Assign Child class object to Parent reference
Parent pc = new Child();
pc.display();
}
}
Output :
Static is a Non Access Modifier. Static can be applied to variable, method, nested class and
initialization blocks (static block).
A Static variable gets memory allocated only once during the time of class loading.
All the instance of the class share the same copy of the variable, a static variable can be accessed
directly by calling “<<ClassName>>.<<VariableName>>” without need to create instance for the class.
value of a static variable will be common for all instances
Local variables cannot be assigned as static it will throw compile time error “illegal start of expression”,
as the memory cannot be assigned during class load.
3. What is a static method ?
A static method belongs to class rather than object. It can be called directly by using the
classname “<<ClassName>>.<<MethodName>>”
A static method can access static varaibles directly and it cannot access non-staticvariables and can only
call a static method directly and it cannot call a non-static method from it.
Only the main() method which is static will be called by the JVM automatically, Not all the static method
will be called automatically.
Yes. You can have static block alone in the class without a main method.
No, you cannot override a static method in Java as there will not be any Run-time
Polymorphism happening. Read More..
If our main() method is not declared as static then the JVM has to create object first and call which
causes the problem of having extra memory allocation.
A static block, is a block of code inside a Java class that will be executed when a class is first loaded in to
the JVM. Mostly the static block will be used for initializing the variables.
Static block will be called only one while loading and it cannot have any return type, or any keywords
(this or super).
class test
{
int val;
static{
val = 100;
}
}
9. Can we have multiple static blocks in our code ?
Yes, we can have more than one static block in our code. It will be executed in the same order it is
written.
In Java only nested classes are allowed to be declared as static, a top level class cannot be declared as
static.
Even though static classes are nested inside a class, they doesn’t need the reference of the outer class
they act like outer class only. Read More..
In general a static method means that “The Method belong to class and not to any particular object”
but a constructor is always invoked with respect to an object, so it makes no sense for a constructor to
be static.
Suppose when you have a concrete method in a abstract class then that method can be static.
Suppose we have a class like below
No, Interface cannot have static methods in it because all methods are implicitly abstract. This is why
an interface cannot have a static method.
void welcome()
{
System.out.println("Welcom to JavaInterviewPoint");
}
}
The welcome() method which we tried calling is an instance-level method, we do not have
an instance to call it . static methods belong to the class, non-static methods belong to instances of
the class and hence it throws the error ” non-static method cannot be referenced from a static context “.
Yes we can define main method like static public void main(String[] args){}
Order of modifiers we can change.
1) What is an exception?
Exception is an abnormal condition which occurs during the execution of a program and disrupts
normal flow of the program. This exception must be handled properly. If it is not handled, program
will be terminated abruptly.
2) How the exceptions are handled in java? OR Explain exception handling mechanism in
java?
Exceptions in java are handled using try, catch and finally blocks.
try block : The code or set of statements which are to be monitored for exception are kept in this
block.
catch block : This block catches the exceptions occurred in the try block.
finally block : This block is always executed whether exception is occurred in the try block or not and
occurred exception is caught in the catch block or not.
3) What is the difference between error and exception in java?
Errors are mainly caused by the environment in which an application is running. For example,
OutOfMemoryError happens when JVM runs out of memory. Where as exceptions are mainly caused
by the application itself. For example, NullPointerException occurs when an application tries to access
null object.
No. We shouldn’t write any other statements in between try, catch and finally blocks. They form a
one unit.
1
try
2
{
3
// Statements to be monitored for exceptions
4
}
5
6 //You can't keep statements here
7
8 catch(Exception ex)
9 {
11 }
12
//You can't keep statements here
13
14
finally
15
{
16
// This block is always executed
17
}
18
No, It shows compilation error. The try block must be followed by either catch or finally block. You
can remove either catch block or finally block but not both.
6) There are three statements in a try block – statement1, statement2 and statement3.
After that there is a catch block to catch the exceptions occurred in the try block. Assume
that exception has occurred in statement2. Does statement3 get executed or not?
No. Once a try block throws an exception, remaining statements will not be executed. control comes
directly to catch block.
When you are keeping multiple catch blocks, the order of catch blocks must be from most specific to
most general ones. i.e sub classes of Exception must come first and super classes later. If you keep
super classes first and sub classes later, compiler will show unreachable catch block error.
2 {
10 {
12 }
13
14 catch(NumberFormatException ex)
{
15
//Compile time error
16
//This block becomes unreachable as
17
//exception is already caught by above catch block
18
}
19
}
20 }
21
22
The exceptions which occur at run time are called as run time exceptions. These exceptions are
unknown to compiler. All sub classes of java.lang.RunTimeException and java.lang.Error are run time
exceptions. These exceptions are unchecked type of exceptions. For example,
NumberFormatException, NullPointerException, ClassCastException,
ArrayIndexOutOfBoundException, StackOverflowError etc.
OutOfMemoryError is the sub class of java.lang.Error which occurs when JVM runs out of memory.
Checked exceptions are the exceptions which are known to compiler. These exceptions are checked
at compile time only. Hence the name checked exceptions. These exceptions are also called compile
time exceptions. Because, these exceptions will be known during compile time.
Unchecked exceptions are those exceptions which are not at all known to compiler. These exceptions
occur only at run time. These exceptions are also called as run time exceptions. All sub classes of
java.lang.RunTimeException and java.lang.Error are unchecked exceptions.
No, it gives unreachable code error. Because, control is returning from the finally block itself.
Compiler will not see the statements after it. That’s why it shows unreachable code error.
14) 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.
Yes, we can throw an exception manually using throw keyword. Syntax for throwing an exception
manually is
throw InstanceOfThrowableType;
Below example shows how to use throw keyword to throw an exception manually.
1
try
2 {
4
6 }
7 catch(NumberFormatException ex)
{
8
System.out.println("explicitly thrown NumberFormatException object will be caught here"
9
}
10
Exceptions raised in the try block are handled in the catch block. If it is unable to handle that
exception, it can re-throw that exception using throw keyword. It is called re-throwing an exception.
1
try
2
{
3 String s = null;
5 }
6 catch(NullPointerException ex)
{
7
System.out.println("NullPointerException is caught here");
8
9
throw ex; //Re-throwing NullPointerException
10
}
11
Because finally block is always executed whether exceptions are raised in the try block or not and
raised exceptions are caught in the catch block or not. By keeping the clean up operations in finally
block, you will ensure that those operations will be always executed irrespective of whether exception
is occurred or not.
19) What is the difference between final, finally and finalize in java?
Click here to see the differences between final, finally and finalize in java.
20) How do you create customized exceptions in java?
Click here to see about customized exceptions in java.
21) What is ClassCastException in java?
ClassCastException is a RunTimeException which occurs when JVM unable to cast an object of one
type to another type.
22) What is the difference between throw, throws and throwable in java?
Click here to see the differences between throw, throws and throwable in java.
23) What is StackOverflowError in java?
No. If a super class method is throwing an unchecked exception, then it can be overridden in the sub
class with same exception or any other unchecked exceptions but can not be overridden with
checked exceptions.
java.lang.Throwable is the super class for all types of errors and exceptions in java.
27) What are the legal combinations of try, catch and finally blocks?
1)
1
try
2 {
3 //try block
4 }
5 catch(Exception ex)
6 {
//catch block
7
}
8
2)
1
try
2 {
3 //try block
4 }
5 finally
6 {
//finally block
7
}
8
3)
1
try
2
{
3
//try block
4 }
5 catch(Exception ex)
6 {
7 //catch block
8 }
finally
9
{
10
//finally block
11
}
12
printStackTrace() method is used to print the detailed information about the exception occurred.
Q13. What are the rules we need to follow when overriding a method
that throws an exception?
When the parent class method doesn’t throw any exceptions, the child class method can’t throw any
checked exception, but it may throw any unchecked.
When the parent class method throws one or more checked exceptions, the child class method can
throw any unchecked exception; all, none or a subset of the declared checked exceptions, and even
a greater number of these as long as they have the same scope or narrower.
When the parent class method has a throws clause with an unchecked exception, the child class
method can throw none or any number of unchecked exceptions, even though they are not related.