Oops concepts
|
1. What is Data hiding?
A) Outside person cannot access our data directly. By using private modifier we can achieve Data hiding.
2. What is Abstraction?
A) Hiding internal implementation details and just highlight the set of services what we are offering is called abstraction.
3. What is Encapsulation?
A) Encapsulating data and corresponding methods (behavior) into single module is called encapsulation.
4. Explain the advantages and disadvantages of Encapsulation?
A) The main advantage of encapsulation are
A) Outside person cannot access our data directly. By using private modifier we can achieve Data hiding.
2. What is Abstraction?
A) Hiding internal implementation details and just highlight the set of services what we are offering is called abstraction.
3. What is Encapsulation?
A) Encapsulating data and corresponding methods (behavior) into single module is called encapsulation.
4. Explain the advantages and disadvantages of Encapsulation?
A) The main advantage of encapsulation are
•
we can achieve security.
•
enhancement will become easy.
•
improve modularity of the application.
disadvantage:
•
it increases the length of the code and
slowdown execution.
5. What is tightly encapsulated class?
A) Every data members declared as private is classed tightly encapsulated class.
6. What is IS-A relationship?
A) It is also known as inheritance.
7. Which keyword is used for IS-A relationship?
A) By using extends keyword we can implement IS-A relationship.
8. What are various advantages of IS-A relationship?
A) Re-usability of code.
9. Explain about HAS-A relationship?
A) Has -A relationship is known as composition or aggregation.
10. What is composition?
A) Whenever container object is destroyed all contained object will be destroyed automatically that is without existing container object there is no chance of existing contained object.
11. What is aggregation?
A) Whenever container object destroyed there is no guarantee of destruction of contained objects that is without existing container object there may be chance of existing contained object. Container object just maintains references of contained objects.
12. What is method signature?
•
method name and parameter
list are part of method signature, thus No, return type is not part of method
signature
13. What is
overloading?
Overloading can be done in two places 1) methods
2) Constructors
Method Overloading:
•
Overloading in java occurs when methods in a same class or in
child classes shares a same name with a ‘difference in number of arguments’ or
‘difference in argument type’ or both.
Argument lists could differ in
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters.
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters.
•
Method overloading is
also known as Static Polymorphism.
•
Points to Note:
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.
1. Static Polymorphism is also known as compile time binding or early binding.
2. Static binding happens at compile time. Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.
Constructor
overloading:
•
Overloaded constructors are
differentiated on the basis of their type of parameters or number of
parameters.
•
In case of method overloading you have
multiple methods with same name but different signature, whereas in Constructor
overloading you have multiple constructor with different signature but only
difference is that Constructor doesn't have return type in Java.
•
Constructor overloading is
done to construct object in different ways.
14. What are various rules satisfied by overloaded methods?
Argument lists could differ in
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters
15. What is static polymorphism (or) compile time polymorphism (or) early binding?
•
Method overloading is
also known as Static Polymorphism.
16. Differentiate IS-A
and HAS-A relationships?
‘is – a’
relationship(association)
|
‘has – a’ relationship(aggregation)
|
The ‘is – a’ relationship is expressed with Inheritance.
|
The ‘has – a’ relationship is expressed with Composition.
|
Class Inheritance.
|
Object Composition.
|
Inheritance uses extend keyword
|
Composition uses new keyword.
|
Inheritance is uni – directional. For example House is a Building. But Building is
not House.
|
Composition is used when House has a Bathroom. It is incorrect to say House is a bathroom.
Which simply uses instance variable that refer to the other object
|
Is a [House is a Building]
class Building
{
……….
}
class House extends Building
{
………..
}
|
Has a [House has a Bathroom]
class Bathroom
{
…………
}
class House
{
Bathroom room=new Bathroom();
………..
}
|
17. Is it possible to overload main() method?
•
Yes, you can overload main method in Java.
•
But the program doesn't execute the overloaded
main method when you run your program. You have to call the overloaded main
method from the actual main method.
18. In overloading
whether jvm or compiler is responsible for method resolution?
•
Method
overloading is defining several methods in the same class
that accept different numbers and types of parameters.
•
In this
case, the actual method called is decided at compile-time, based on the number
and types of arguments.
•
For
instance, the method System.out.println() is
overloaded, so that you can pass int
as well as Strings, and it will call
a different version of the method.
19. What is overriding?
•
Method
overriding is when a child class redefines the same
method as in parent class, with the same parameters but with different
implementation.
Example:
The
standard Java class java.util.LinkedHashSet extends java.util.HashSet. The
method add() is overridden in LinkedHashSet. If you have a variable that is of
type HashSet, and you call its add() method, it will call the appropriate
implementation of add(), based on whether it is a HashSet or a LinkedHashSet.
This is called polymorphism.
20. What is run-time polymorphism or dynamic polymorphism or late binding?
20. What is run-time polymorphism or dynamic polymorphism or late binding?
•
Polymorphism is the
capability of an action or method to do different things based on the object
that it is acting upon.
•
In other words, polymorphism allows you define
one interface and have multiple implementations. This is one of the basic
principles of object oriented programming.
•
In method overriding both the classes (base
class and child class) has same method, compile doesn’t figure out which method
to call at compile-time. In this case JVM(java virtual machine) decides which
method to call at runtime that’s why it is known as runtime or dynamic
polymorphism.
21. What are various
rules satisfied by overriding methods?
Rules
for method overriding:
•
The argument list should be exactly the same
as that of the overridden method.
•
The return type should be the same or a
subtype of the return type declared in the original overridden method in the
super class.
•
The access level cannot be more restrictive
than the overridden method's access level.
Example: if the super class
method is declared public then the overriding method in the sub class cannot be
either private or protected.
•
Instance methods can be overridden only if
they are inherited by the subclass.
•
A
method declared final cannot be overridden.
•
A
method declared static cannot be overridden but can be re-declared.
•
If a method cannot be inherited, then it
cannot be overridden.
•
A subclass in a different package can only
override the non-final methods declared public or protected.
•
An overriding method can throw any unchecked
exceptions, regardless of whether the overridden method throws exceptions or
not. However the overriding method should not throw checked exceptions that are
new or broader than the ones declared by the overridden method. The overriding
method can throw narrower or fewer exceptions than the overridden method.
•
Constructors
cannot be overridden.
There are few rules which need to be followed
while overriding any method in Java, failure to follow these rules result in
compile time error in Java.
•
First and most important rule regarding method
overriding in Java is that you can only override method in sub
class. You cannot override method in same class.
•
Second important rule of method overriding in
Java that name and signature of method must be same in Super class and Sub
class or in interface
and its implementation.
•
Third rule to override method in Java is that
overriding method cannot reduce accessibility of overridden method in Java. For
example if overridden method is public than overriding method cannot be
protected, private or package-private; But opposite is true overriding method
can increase accessibility of method in Java, i.e. if overridden method is
protected than overriding method can be protected or public.
•
Another worth noting rule of method
overriding in Java is that overriding method cannot throw checked
Exception which is higher in hierarchy than overridden
method. Which means if overridden method throws IOException than overriding
method cannot throw java.lang.Exception in its throws clause because
java.lang.Exception comes higher than IOException in Exception hierarchy. This
rule doesn't apply to RuntimeException in Java, which is not even need to be
declared in throws clause in Java.
•
You cannot override private,
static
and final
method in Java. private and static method are bonded during
compile time using static binding in Java
and doesn't resolve during runtime. Overriding final method in Java is
compile time error. Though private and static method can be hidden if you
declare another method with same and signature in sub class.
•
Overridden method is called using dynamic
binding in Java at runtime based upon type of Object. As
shown in following example of method overloading.
•
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.
•
Always
use @Override annotation while overriding method in Java. 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.
22. Is it possible to override the following methods?
final methods:
no it cannot be overridden but it can be
inherited.
abstract methods: yes
synchronized methods:
•
Synchronized is the
implementation detail of a method. You can override a sync method with a method
without declaring that as sync and vice versa. The same holds true for the
overloading also.
native methods:
•
The native methods can be
overridden just like any other methods, unless they are declared final. Turns out that native method
can be overridden by non-native, and vice-versa too. native appears to not be a
part of the signature.
strictfp methods:
private methods: no
23. What are co-variant return types?
23. What are co-variant return types?
•
Before Java5, it was not possible to override
any method by changing the return type.
•
But now, since Java5, it is possible to
override method by changing the return type if subclass overrides any method
whose return type is Non-Primitive but it changes its return type to subclass
type.
•
The covariant return type in java, allows
narrowing down return type of the overridden method.
•
This feature will help to avoid down casting
on the client side. It allows programmer to program without the need of type
checking and down casting.
•
The covariant return type always works only
for non-primitive return types.
The Clone method will return the object where
we need to downcast the Object to the subclass type. After Java5, we can
override the clone method to return the object of subclass type.
24. While overriding
is it compulsory to maintain same return type?
•
Since Java5, it is possible to override method
by changing the return type if subclass overrides any method whose return type
is Non-Primitive but it changes its return type to subclass type.
25. In overriding who is responsible for method resolution?
26. What is dynamic method dispatch?
27. If parent class method throws some checked exception while overriding is it compulsory should throw child class method the same checked exception?
•
An overriding method can throw any unchecked
exceptions, regardless of whether the overridden method throws exceptions or
not. However the overriding method should not throw checked exceptions that are
new or broader than the ones declared by the overridden method. The overriding
method can throw narrower or fewer exceptions than the overridden method.
28. Is it possible to
overriding constructor?
•
Constructors are not normal
methods and they cannot be "overridden".
29. Is it possible to
override non-abstract method as abstract?
•
You cannot require an
override of a non-abstract method.
30. Is it possible to override a var-arg method with a general
method?
31. Is it possible to override static method?
31. Is it possible to override static method?
•
private and static method are bonded during
compile time using static binding in Java and doesn't resolve during runtime.
•
Though private and static method can be hidden
if you declare another method with same
signature in sub class.
32. What is method hiding?
•
Hiding is based on the early binding. More
clearly, the method or member to be called or used, is decided during compile
time.
33. Explain differences b/w overriding and method hiding?
•
Over-riding basically
supports late binding. Therefore, which method will be called is decided at run
time. It is for non-static methods.
•
Hiding is for all other
members (static methods , instance members, static members). It is based on the
early binding. More clearly, the method or member to be called or used is
decided during compile time.
34. Is it possible to override a main() method?
•
No. We can not override main
method. As it is static and static methods can not be overridden
35. Is it possible to override a variable?
•
In short, no, there is no way
to override a class variable.
•
You do not override class
variables in Java you hide them. Overriding is for instance methods. Hiding is
different from overriding.
36. Who is responsible for variable resolution?
37. What are the key differences b/w overriding and overloading?
37. What are the key differences b/w overriding and overloading?
•
private:
A java private method cannot be overridden because, it is not accessible to an
inheriting class.
•
final:
Method overloading a Java final method is possible but overriding a final
method is not allowed.
•
final:
Two methods with same parameters list and in one method we have parameters ‘final’,
in this case two methods are not different methods and overloading is not
possible.
•
static:
Method overloading a Java static method is possible but overriding a static
method is not possible.
•
static:
Overriding is in the context of objects (instances) and inheritance. A method
declared as static belongs to the whole class (common for all objects). So
there is no point of overriding it in sub-class.
•
static:
In overloading if two methods are different only by a static modifier then it’s
not possible to overload. The arguments list must be different.
38. Explain various activities which are executed while loading the class?
39. Whenever we are loading child class is it required to load parent class?
40. Whenever we are loading parent class is it required to load child class?
41. What is the purpose of static block and explain its requirement with an example?
Static block
•
A static block is
a block that is executed only once. Anything declared static isn't a part
of the object. So, a static block similarly contains code that executes only
one time no matter how many times you create an object for that class.
Example:
loading the driver classes in JDBC. You need to do them only once, throughout
the entire program.
1. Static block gets executed every time when
the class loads into memory not every time an object is created.
2. You cannot declare methods in the static
block, however you can use labeled blocks for code classification.
3. Static block executes in the main thread.
4. The variables you declare in a static block
aren't a part of the object. They are not even the static variables of the
class. They just belong to that block only.
5. You can make method calls in a static block.
6. Static blocks are executed in the order they
are written.
42. Is it possible to take multiple static blocks in the same java class?
•
You can define multiple
static blocks. But I don't think it is really necessary.
•
But if you define, then they
will be executed sequentially. I mean the static block defined first will
execute first and the next block will execute next.
•
It helps in modularization of your
initialization code, which in turn helps in better understanding and readable
nature of the code.
43. When the static blocks will be executed?
44. Without using main() method is it possible to print some statements to console?
45. Without using main() and static blocks is it possible to print some statements?
46. What is instance block when it will be executed?
44. Without using main() method is it possible to print some statements to console?
45. Without using main() and static blocks is it possible to print some statements?
46. What is instance block when it will be executed?
Instance blocks
•
Instance blocks are
different. Unlike static blocks, they execute every time you create an object
for a class.
•
The instance block contains
code that needs to execute every time an object is created no matter through
which constructor.
•
It executes just before the constructor is
executed and just after the super() is called (after the super class'
constructor is activated).
•
The concept of instance
blocks is best applied in anonymous inner classes, where we cannot declare a
constructor.
47. Difference b/w instance block and static block?
48. Whenever we are creating an object what are various steps will be executed internally?
49. Difference b/w constructor and instance block?
•
The code in the initializer
is inserted after the call
to the super class constructor and before the
rest of the constructor code.
•
The first operation of any
constructor is to invoke a super class constructor. If a constructor is called
explicitly, super(...), the specified constructor is used.
•
If no constructor is
explicitly invoked, the default constructor (with no arguments) is invoked in
the super class. If no such constructor exists, it is a compile time error.
•
After this explicit or
implicit constructor invocation, instance initializer are invoked in the order
they appear in source code (yes, you can have more than one initializer).
Initialization
blocks are places where you can perform operations
like initialization of variables or execution of some statements. There are two
kinds of initialization blocks
•
static initialization blocks
•
instance initialization blocks.
As their names suggest,
•
static initialization blocks are static and
hence they belong to a particular class and not to the instances of class. They
are defined as static { //some statements here }
•
Instance initialization blocks do not belong
to a class and they are executed every time a new instance of the class is
created. They are defined as {//some statements here}
There are certain rules regarding order of
execution of initialization blocks and constructor.
•
Initialization blocks run in the order they
appear in the program
•
Static initialization blocks run when class is
loaded in JVM
•
Instance initialization blocks run every time
a new instance is created.
•
Instance initialization blocks run AFTER the
super constructor has completed executing and BEFORE current class constructor.
•
They can be used to perform operations those
are common to constructors.
50. What is coupling?
Coupling
•
By definition coupling is the degree to which
one class has knowledge of another or in other words one class has a dependency
upon another.
•
Tight
coupling occurs when a dependent concrete class contains a pointer to another
concrete class that provides the required behavior and should be avoided.
•
The problem here is that any changes to one
class could impact the other and the person making the changes may be
completely unaware of this and thus unknowingly break the class. So how do we
avoid this scenario? We design by
contract by using an interface to specify an API for other classes to use .
/*
Tight coupling example
*/
class A {
int
i;
B b
= new B();
i =
b.value; //
No encapsulation of this variable in class B!
}
class B {
public int value; // Should be private and be accessed through
public getters and setters
}
51. Is it recommended tight coupling or loose coupling?
52. What is cohesion?
Cohesion
•
Cohesion is the degree to which components of
a class belong together to fit a particular role.
•
What we want to avoid is low cohesion where a
class incorporates several different aspects.
•
A class
that tries to do many things comes with higher maintenance and lower
reusability.
/*
Low cohesion example
*/
class AllInStaff
{
void
getStaffSalary();
void
getStaffDetails();
void
getStaffSalesReport();
}
/*
High cohesion example
*/
class Accounts {
void
getStaffSalary();
...
}
class Personnel {
void
getStaffDetails();
...
}
class SalesReporting {
void
getStaffSalesReport();
...
}
What
is cohesion?
•
Cohesion is simply quality of a thing being
stuck together well.
•
We would say that something is highly cohesive
if it has a clear boundary and all of it is contained in one place.
Example:
•
a baseball is very cohesive. Everything
that makes up a baseball is in one little round orb.
•
The internet is not cohesive. It is hard
to define and it is scattered all over the place.
What
is decoupling?
•
Decoupling is the quality of a thing not
relying on other things.
•
We would say that something is decoupled if it
does not depend on anything but itself. Something would be highly coupled
if it had many different dependencies.
Example:
consider the motherboard in your computer. It is not decoupled. It
contains specific slots for RAM, for a CPU, for video cards, etc. If
those components change in their shape or kind, they may not work with the
motherboard.
•
We like loosely coupled software because it
reduces the impact of a change in one module across other modules.
•
Loosely
coupled software is also easier to reuse, because it doesn’t have many other
dependencies to be included.
•
In the very general sense, as you decrease
coupling, you increase cohesion and vice versa.
53. Is it recommended high cohesion or low cohesion?
54. Explain about object type casting and what are various rules we have to follow while performing type casting?
54. Explain about object type casting and what are various rules we have to follow while performing type casting?
Object Reference Type Casting
•
In java object typecasting one object reference can
be type cast into another
object reference.
•
The cast can be to its
own class type or to one of its subclass or super class types or interfaces.
There are compile-time rules and runtime rules for casting in java.
There can be 2 casting java
scenarios
•
Upcasting
•
Downcasting
•
When we cast a reference
along the class hierarchy in a direction from the root class towards the
children or subclasses, it is a downcast.
•
When we cast a reference
along the class hierarchy in a direction from the sub classes towards the root,
it is an upcast. We need not use a cast operator in this case.
The compile-time rules
are there to catch attempted casts in cases that are simply not possible.
This happens when we try to attempt casts on objects that are totally unrelated
(that is not subclass super class relationship or a class-interface
relationship) At runtime a ClassCastException is thrown if the object being
cast is notcompatible with the new type it is being cast to.
Casting Object References: Implicit Casting using a Compiler
In general an implicit cast
is done when an Object reference is assigned (cast) to:
* A reference variable whose
type is the same as the class from which the object was instantiated.
An Object as Object is a super class of every Class.
* A reference variable whose type is a super class of the class from which the object was instantiated.
* A reference variable whose type is an interface that is implemented by the class from which the object was instantiated.
* A reference variable whose type is an interface that is implemented by a super class of the class from which the object was instantiated.
An Object as Object is a super class of every Class.
* A reference variable whose type is a super class of the class from which the object was instantiated.
* A reference variable whose type is an interface that is implemented by the class from which the object was instantiated.
* A reference variable whose type is an interface that is implemented by a super class of the class from which the object was instantiated.
Consider an interface
Vehicle, a super class Car and its subclass Ford. The following
example shows theautomatic conversion of object references handled by
the compiler
Assigning one data type to another or one object to another is
known as casting. Java supports
two types of casting – data type casting and object casting.
Java
permits to assign objects of different classes one to another subject to some
conditions.
1. Same class objects can be assigned one to another and it is
what we have done with Officer1 class.
2. Subclass object
can be assigned to a super class object and this casting is done implicitly.
This is known as upcasting (upwards
in the hierarchy from subclass to super class).
3. Java does not
permit to assign a super class object to a subclass object (implicitly) and
still to do so, we need explicit
casting. This is known as downcasting (super
class to subclass). Downcasting requires explicit conversion.
55. Is it possible to type cast parent object to the child type?
56. Is it possible to type cast child object to the parent type?
57. Explain main important oops concepts?
Encapsulation
•
Encapsulation means putting
together all the variables (instance variables) and the methods into a single
unit called Class. It also means hiding data and methods within an Object.
Encapsulation provides the security that keeps data and methods safe from inadvertent
changes.
Inheritance
•
The process by which one
class acquires the properties and functionalities of another class.
•
Inheritance provides the idea
of reusability of code and each sub class defines only those features that are
unique to it.
•
Inheritance is a mechanism of
defining a new class based on an existing class.
•
Inheritance enables reuse of
code.
•
Inheritance implements the “Is-A” or “Kind Of/ Has-A” relationship.
Note: The biggest advantage of Inheritance is that, code in
base class need not be rewritten in the derived class.
The member variables and methods of the base class can be used in the derived class as well.
The member variables and methods of the base class can be used in the derived class as well.
Polymorphism
•
Polymorphism is
a feature that allows one interface to be used for a general class of actions.
It’s an operation may exhibit different behavior in different instances.
•
Polymorphism is extensively
used in implementing inheritance.
Types
of Polymorphism
1) Static Polymorphism
2) Dynamic Polymorphism
1) Static Polymorphism
2) Dynamic Polymorphism
Static
Polymorphism:
Function
Overloading:
•
Within same class more than
one method having same name but differing in signature.
•
Resolved during compilation
time.
•
Return type is not part of
method signature.
Dynamic
Polymorphism
Overriding:
•
Keeping the signature and
return type same. method in the base class is redefined in the derived class.
•
Resolved during run time.
•
Which method to be invoked is
decided by the object that the reference points to and not by the type of the
reference.
Abstract
Classes
Note
2: Abstract Class cannot
be instantiated.
To use an abstract class one has to first derive another class from this abstract class using inheritance and then provide the implementation for the abstract methods.
Note 3: If a derived class does not implement all the abstract methods (unimplemented methods), then the derived class is also abstract in nature and cannot be instantiated.
To use an abstract class one has to first derive another class from this abstract class using inheritance and then provide the implementation for the abstract methods.
Note 3: If a derived class does not implement all the abstract methods (unimplemented methods), then the derived class is also abstract in nature and cannot be instantiated.
58. What is the purpose of constructor?
•
Constructors are used to
initialize the instances of your classes.
•
You use a constructor to
create new objects often with parameters specifying the initial state or other
important information about the object
From the official Java tutorial:
•
A class contains constructors that are invoked to create objects
from the class blueprint.
•
Constructor declarations look
like method declarations—except that they use the name of the class and have no
return type.
59. Explain about default constructor and its prototype?
•
Default constructor refers to
a constructor that is automatically created by compiler in the absence of
explicit constructors.
•
You can also call a
constructor without parameters as default constructor because all of its class
instance variables are set to default values.
60. Is compiler generates default constructor always?
61. Is it possible to take return type for the constructor?
62. If we are taking return type to the constructor what will happen?
63. Explain about super() and this()?
61. Is it possible to take return type for the constructor?
62. If we are taking return type to the constructor what will happen?
63. Explain about super() and this()?
•
This() is used to invoke a constructor of the
same class. super() is used to invoke asuperclass constructor.
64. Is it possible to overload constructor?
65. Is inheritance concept applicable for constructors?
65. Is inheritance concept applicable for constructors?
•
constructors are never
inherited
66. What are various
modifiers applicable for constructors?
Only public, protected, private and default (no modifier) are
legal when declaring constructors
67. Where we can use private constructors?
67. Where we can use private constructors?
•
to prevent instantiation outside of the
object, in the following cases:
•
singleton
•
factory method
•
static-methods-only (utility) class
•
constants-only class
•
To prevent sub classing (extending). If you
make only a private constructor, no class can extend your class, because it
can't call the super () constructor. This is some kind of a synonym for final
•
Overloaded constructors - as a result of
overloading methods and constructors, some may be private and some public.
Especially in case when there is a non-public class that you use in your
constructors, you may create a public constructor that creates an instance of
that class and then passes it to a private constructor.
Private Constructors can be defined in the
Java for the following reasons
•
To have control on the instantiation of the
Java objects, it won’t allow you to create an instance of an object.
•
It won’t allow the class to be Sub classed
•
This has a special advantage when implementing
the singleton Pattern, Private
constructors are used for it and have a control on the creating the instance
for the whole application.
•
When you want to have a class with all
constants defined and does not require its instance any more, then we declare
that class as a private constructor.
68. What is singleton class give an example?
•
We can make constructor as private. So that we
cannot create an object outside of the class.
•
This property is useful to create singleton
class in java.
•
Singleton pattern helps us to keep only one
instance of a class at any time.
•
The purpose of singleton is to control object
creation by keeping private constructor.
Example: if you have a license for only one connection
for your database or your JDBC driver has trouble with multithreading, the
Singleton makes sure that only one connection is made or that only one thread
can access the connection at a time.
//
File Name: Singleton.java
public
class Singleton {
private static Singleton singleton = new
Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){ }
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness
*/
protected static void demoMethod( ) {
System.out.println("demoMethod for
singleton");
}
}
There are only two points in the definition of
a singleton design pattern,
•
there should be only one instance allowed for
a class and
•
We should allow global point of access to that
single instance.
•
You need to be careful with multiple threads.
If you don’t synchronize the method which is going to return the instance then,
there is a possibility of allowing multiple instances in a multi-threaded
scenario. Do the synchronization at block level considering the performance
issues.
•
Using serialization,
single instance contract of the singleton pattern can be violated. You can
serialize and de-serialize and get a new instance of the same singleton class.
Using java api, you can implement the below method and override the instance
read from the stream. So that you can always ensure that you have single
instance.
69. Is it possible to create our own singleton class and explain
the process?
•
Yes
70. What is factory
method?
Provides an abstraction or an interface and
lets subclass or implementing classes decide which class or method should be
instantiated or called, based on the conditions or parameters given.
Where
to use & benefits
•
Connect parallel class hierarchies.
•
A class wants its subclasses to specify the
object.
•
A class cannot anticipate its subclasses,
which must be created.
•
A family of objects needs to be separated by
using shared interface.
•
The code needs to deal with interface, not
implemented classes.
•
Hide concrete classes from the client.
•
Factory methods can be parameterized.
•
The returned object may be either abstract or
concrete object.
•
Providing hooks for subclasses is more
flexible than creating objects directly.
•
Follow naming conventions to help other
developers to recognize the code structure.
•
Related patterns include
•
Abstract Factory ,
which is a layer higher than a factory method.
•
Templa te
method, which defines a skeleton of an algorithm to
defer some steps to subclasses or avoid subclasses
71. Explain about recursive constructor invocation?
72. If parent class constructor throws some checked exception is it compulsory to require to throw that exception by child class constructor?
73. Is the first line in constructor is always super?
•
According to Java this() and super() should be
the first statement in constructor. Now the point is we cannot write both at
once as a first line. If u write this() and not super, dont expect that super
will be called implicitly. It is as simple as it is. U have no option to write
them together in single constructor body
74. Is it possible to write a constructor in abstract class?
yes
75. We can’t create an object of abstract class what is the need of constructor in abstract class?
75. We can’t create an object of abstract class what is the need of constructor in abstract class?
1) Abstract classes have constructors and
those constructors are always invoked when a concrete subclass is instantiated.
We know that when we are going to instantiate a class, we always use
constructor of that class. Now every constructor invokes the constructor of its
super class with an implicit call to
super().
2) We know constructor is also used to
initialize fields of a class. We also know that abstract classes may contain
fields and sometimes they need to be initialized
somehow by using constructor.
•
These constructors are for initializing
members in the abstract class before the child class can be initialized
76. Is it possible to place constructor in an interface?
•
It is not possible to define a constructor
signature in a java interface.
•
If you want to assure a construction of
objects using a particular signature your options are the following design
patterns
77.
Can we overload static method in Java Program?
•
Yes, we can overload static method in Java. In
terms of method
overloading static method are just like normal methods
and in order to overload static
method you need to provide another static method
with same name but different method signature.
78. Difference between Static
binding and Dynamic binding in java?
•
Static binding in Java occurs
during compile time while dynamic binding occurs during runtime.
•
Static binding uses
type(Class) information for binding while dynamic binding uses instance of
class(Object) to resolve calling of method at run-time.
•
Overloaded methods are bonded
using static binding while overridden methods are bonded using dynamic binding
at runtime.