Java Interview Questions Part-1
Java Interview Questions Part-1
There are four principle concepts upon which object oriented design and
programming rest. They are:
a) Abstraction
b) Encapsulation
c) Inheritance
d) Polymorphism
What is Abstraction?
2) Create public accessor methods and use these methods from within the calling
code.
3) Use the JavaBeans naming convention of getter and setter.
Advantages of encapsulation:
It improves maintainability and flexibility and re-usability.
1.
The fields can be made read-only (If we dont define setter methods in the
class) or write-only (If we dont define the getter methods in the class). For e.g. If
we have a field(or variable) which doesnt need to change at any cost then we
simply define the variable as private and instead of set and get both we just need
to define the get method for that variable. Since the set method is not present
there is no way an outside class can modify the value of that field.
2.
User would not be knowing what is going on behind the scene. They would only
be knowing that to update a field call set method and to read a field call get
method
but what these set and get methods are doing is purely hidden from them.
2.
The behavior of this object is what which is useful for the external world or
other objects.
3.
4.
The set of functions an object exposes to other objects or external world acts
as the interface of the object.
What is Inheritance
Difination : Deriving new classes from existing classes such that the new classes
acquire all the features of existing classes is called inheritance.
Difination Inherit the feature of any class by making some relations between the
class/interface is known as inheritance
Difination Inheritance is the process by which objects of one class acquire the
properties of objects of another class.
a) A class that is inherited is called a super class.
b) The class that does the inheriting is called a subclass.
c) Inheritance is done by using the keyword extends.
d) The two most common reasons to use inheritance are:
To promote code reuse
To use polymorphism
A subclass does not inherit the private members of its parent class.
private methods are not inherited (and therefore cannot be overriden)
- non static class methods cannot be executed without instance of the class
What is Polymorphism
Dfination: Polymorphism is briefly described as "one interface, many
implementations." Or one method with multiple implementation
There are two types of polymorphism one is Run time polymorphism. and the
other is Compile time polymorphism
Runtime time polymorphism is done using inheritance and interface.
Compile time polymorphism is method overloading.
a) Method overloading
b) Method overriding through inheritance
c) Method overriding through the interface
Can have different return types but in that case it is mandatory to have
different argument list.
c)
d)
For e.g. if the Access Modifier of base class method is public then the overriding
method (child class method ) cannot have private, protected and default Access
modifier as all of the three are more restrictive than public.
For e.g. This is not allowed as child class disp method is more
restrictive(protected) than base class(public)
b) Instance methods can be overridden only if they are inherited by the subclass.
c) private, static and final methods cannot be overridden as they are local to the
class. private and static method are bonded during compile time using static
binding
But static methods can be re-declared in the sub class, in this case the subclass method would act differently and will have nothing to do with the same
static method of parent class.
d) overriding final method is compile time error. Though private and static method
can be hidden if you declare another method with same and signature in sub
class.
e) If a method cannot be inherited, then that method cannot be overridden.
f) A subclass within the same package as the instance's super class can override
any super class method that is not declared private or final.
g) A subclass in a different package can only override the non-final methods
declared public or protected.
h) Constructors cannot be overridden.
1) you can only override method in sub class. You can not override method in same
class.
2) method name and method signaturs must be same in Super class and Sub class.
7) If you are extending abstract class or implementing interface than you need to
override all abstract method unless your class is not abstract. abstract method
can only be used by using method overriding.
1) Always use @Override annotation while overriding method. Though this is not
rule but its one of the best Java coding practice to follow. From Java 6 you can
use @Override annotation on method inherited from interface as well.
1) The method overloading Argument list should be different. But The method
Overriding Argument list should be same.
2) The Method overloading return type should be different. But The method
Overriding return type should be same.
3) The Method overloading is done in the same class.But method Overring is done
in super class and sup class.
4) private and final methods can be overloaded but they cannot be overridden. It
means a class can have more than one private/final methods of same name but
a child class cannot override the private/final methods of their base class.
5) Static methods can be overloaded which means a class can have more than one
static method of same name. Static methods cannot be overridden, even if you
declare a same static method in child class it has nothing to do with the same
method of parent class.
6) Overloading happens at compile-time But Overriding happens at runtime: The
binding of overloaded method call to its definition has happens at compile-time.
But binding of overridden method call to its definition happens at runtime.
Overridden Method
Must change
Can change
Returns
Exceptio
ns
Can change
Access
Can change
Invocati
on
Reference type
determines which
overloaded version
is selected.
Happens at compile
time.
// From subclass
Super .overridden Method();
17.What is super?
super is a keyword which is used to access the method or member variables
from the super class. If a method hides one of the member variables in its super
class, the method can refer to the hidden variable through the use of the super
keyword. In the same way, if a method overrides one of the methods in its super
class, the method can invoke the overridden method through the use of the super
keyword.
An abstract method is a method that is not contain method body and it is not
contains no implementation.
If any abstract method is not implemented then that sub class should be
declared as abstract. In this case we cannot create an object to the sub class. We
should create anther sub class to this sub class and implement the remaining
abstract method.
e)
f)
g)
The reference of abstract class can be used to refer to object of its sub classes.
h)
The reference of abstract class cannot refer to individual methods of its sub
classes.
i)
j)
If abstract class doesnt have any method implementation, its better to use
interface because java doesnt support multiple class inheritance.
k)
l)
Abstract classes are used to provide common method implementation to all the
subclasses or to provide default implementation.
m)
2.
Subclasses use extends keyword to extend an abstract class and they need to
provide implementation of all the declared methods in the abstract class unless the
subclass is also an abstract class.
But subclasses use implements keyword to implement interfaces and should
provide implementation for all the methods declared in the interface.
3. A subclass can extend only one abstract class but it can implement multiple
interfaces.
4.
5.
Abstract classes can have constructors. But interfaces cant have constructors.
6.
Abstract classes and methods can have access modifiers as public, private,
protected, static. But interface methods are implicitly public and abstract, we cant
use any other access modifiers with interface methods. An interface can not
contain private or protected methods An interface can contain members
variables which are public ,static and final by default.
7.
Abstract classes can extend other class and implement interfaces. But interface
can extend other interfaces only.
8.
We can run an abstract class if it has main() method but we cant run an interface
because they cant have main method implementation.
o You expect that unrelated classes would implement your interface. For
example, the interfaces Comparable and Cloneable are implemented by
many unrelated classes.
o You want to specify the behavior of a particular data type, but not
concerned about who implements its behavior.
o You want to take advantage of multiple inheritance of type.
Interfaces
interfaces.
abstract.
instance variables.
An
abstract
class
constructors .
can
contain
28.When should I use abstract classes and when should I use interfaces?
Use Interfaces when
you need some classes to use some methods which you don't want to be
included in the class, then you go for the interface, which makes it easy to just
implement and make use of the methods defined in the interface.
Use Abstract Class when
If various implementations are of the same kind and use common behavior or
status then abstract class is better to use.
When you want to provide a generalized form of abstraction and leave the
implementation task with the inheriting subclass.
Abstract classes are an excellent way to create planned inheritance hierarchies.
They're also a good choice for non leaf classes in class hierarchies.
What is constructor?
a) Constructor is block of code which is executed at the time of Object creation.
b) Constructors are used to initialize the instance variables of an object.
c) Constructors are required to create objects for a class.
d) Constructor declaration looks like method declaration.
e) constructor name and class name both are same.
f) Constructor do not have return types, not even void also.
g) Constructor can not be inherited and Overridden.
h) Constructors can be classified into two types, default constructors and
parametarized constructors.
i) If you don't define a constructor in a class, then the compiler creates a default
constructor. Default constructors do not contain any parameters.
j) parametarized constructors are required to pass parameters on creation of
objects. We can overload constructors with different data types as its parameters.
k) You can use any access modifier constructor. they can be public, protected or
private. Default or no argument. Constructor in Java can not be abstract, static,
final or synchronized. These modifiers are not allowed for constructor.
constructor is called.
Writing two or more constructors with the same name but different parameters in
same class is called constructor overloading.
In above example we have create two separate object by calling two different
constructors of class ConstructorDemo. If you notice carefully name of
constructor is same as name of class. Also signature of two constructor is
different to each other.
5) You can use any access modifier with Java constructor. they can be public,
protected or private. Default or no argument
constructor has same access modifier as class. You can also prevent a class from
extension by making there constructor private. With private constructor instance
of that class can only be created inside declaring class. Singleton pattern in Java
is popular example of Class with private constructor.
7) Since parent class is initialized before child class in Java, Constructor of parent
class is executed before constructor of child class, that explains why super() is
first statement in default no argument constructor. To understand more about how
class is loaded into memory read How ClassLoader works in Java and When
class is loaded and initialized in JVM.
8) Constructor can throw Exception in Java in fact constructor can declare Exception
in there throws clause but that makes caller to handle or re throw Exception while
creating any instance of Class.
9) Creating object using new() keyword and constructor has there pros and cons. Its
not good in terms of Encapsulation because if you directly create any instance of
class you code is tied up with structure of Constructor and any change in
constructor will require changes in all places where its object gets created.
Standard way is to use factory design pattern in Java which encapsulate object
creation logic and provides better maintenance over time.
10) Unlike C++ there is no destructor in Java. Though objects has finalize method
which suppose to run before objects gets garbage collected but that is not
guaranteed by Java language specification and it may run or may not.
Thats all on What is constructor in Java and important points about constructor in
Java. As you see there is lot of rules and specific information around constructor
but its an important aspect of Java programming language and you must have
good grasp of all constructor specifics in Java. We have also touched concepts
like constructor chaining and constructor overloading which is quite popular on
various Java exams.
1) Constructor name and its class name both are same .But method name and its
class name can be same or different.
2) constructor doesn't have any return type but method has return type and return
something unless its void.
3) Constructors are used to initialize the instance variables of a class. But methods
are used for any general purpose processing or calculations.
4) Constructor is called at the time of creating the object. But method can be called
after creating the object.
5) Constructor is called only once per object. But method can be called several
times on the object.
6) Constructor is called and executed automatically. But method is executed only
class Tax {
double grossIncome;
Tax(double grossIncome){
this.grossIncome = grossIncome;
}
}
The keyword this helps avoid name conflicts, for example this.grossIncome refers to a
member variable grossIncome, while the grossIncome on the right refers to the
argument's value.
34.What are the differences between Contructors and Methods?
Constructors
Methods
Purpo
se
Create an instance of a
class
Modifi
ers
Cannot be abstract,
final, native, static,
or synchronized
Retur
n
Type
Name
static, or synchronized
This
Super
Refers to another
constructor in the same
class. If used, it must
be the first line of the
constructor
Calls the constructor of the
parent class. If used,
36.What are the differences between Class Methods and Instance Methods?
Class Methods
Instance Methods
Instance methods on the other hand
require an instance of the class to exist
static.
Class variables (Static variable) can have only one copy that is shared by
all the different objects of a class, class variables across different object
can have only one value
an instance variable (non static variable) can have every object has its
own personal copy. So, instance variables across different objects can have different
values.
b) Static variables are stored on method area. But Instance variables are
created in the object on heap memory.
c) The static variables are modified it will Effect all the object. But The
instance variables are modified it will not Effect other objects.
1.staticclass
2.staticblock
3.staticmethods
4. static variables
Static Class
A Class can be made static only if it is a nested Class. The nested static class can be
accessed without having an object of outer class.
Static inner class cannot access instance data of outer class.
Static Block
Static block is mostly used for changing the default values of static variables.Static block
gets
executed
when
the
class
is
loaded
in
the
memory.
A class can have multiple Static blocks, which will execute in the same sequence in
which they have been written into the program. Before going to the main method the
static block will execute.
Static block which exactly executed once when the class is first loaded into JVM.
Before going to the main method the static block will execute.
d) Static Methods can access class variables without using object of the class.
e) Static Methods can access non-static methods and non-static variables by using
objects.
f) Static methods can be accessed directly in static and non-static methods.
Restrictions for static method
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static
method directly.
Note: Static variables that are not explicitly initialized in the code are
automatically initialized with a default value. The default value depends on the
data type of the variables.
a) Static variables are also known as Class Variables.
b) Static variables get default values based on the data type.
c) Data stored in static variables is common for all the objects( or instances ) of that
Class.
d) Memory allocation for such variables only happens once when the class is
loaded in the memory.
e) These variables can be accessed in any other class using class name.
f) Unlike non-static variables, such variables can be accessed directly in static
and non-static methods.
What is the different between instance methods and static methods.
Instance methods are methods which act on the instance variables of a class. To
public
protected
Accessible to class
from same
package?
Yes
Yes
Accessible to class
from different
package?
Yes
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
a)
b)
c)
d)
e)
f)
g)
h)