Java Interview Questions and Answers - 4
20. How can we ensure that a resource isn't used by multiple threads simultaneously?
Using synchronized keyword, we can ensure that only one thread can use shared resource at a time and others can get control of the resource only once it is free from the other one using it.21. How can we make copy of a java object?
Object cloning refers to creation of exact copy of an object. It creates a new instance of the class of current object and initializes all its fields with exactly the contents of the corresponding fields of this object.
Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies.22. What is the benefit of using inheritance?
Reusability - Inheritance offers facility to use public methods of base class without rewriting the same.
Extensibility - It extends the base class logic as per business logic of the derived class.
Data hiding - In inheritance, base class can decide to keep some data private so that it cannot be altered by the derived class
Overriding - With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.23. What are two methods to resist a class from inherited in java?
1. By declaring the class as 'final'
2. By declaring all member's of the class private. 24. What is the difference between Stack and Queue?
A stack is based on Last in First out (LIFO) principle while a queue is based on FIFO (First In First Out) principle.