Questions on Encapsulation
- Categories OOPS concepts, OOPS, Java
1. Define Encapsulation.
Ans. Encapsulation is the process of bundling state (instance variables) and behaviour (methods) is a single unit (class).
2. What do you mean by scope and lifetime of a variable?
Ans.
- The scope of a variable defines the area or range or section of the code in which the variable is visible.
- The variables defined within a block are not accessible outside that block.
- The lifetime of a variable refers to how long the variable exists before it is destroyed or goes out of scope.
3. Write in brief about following visibility modes :
- private
- public
- protected
Ans. The access specifer is used to control the accessibility of members of class. The details are as follows:
- private specifier : This keyword converts the data members and member methods in private mode and restricts the accessibility of these members outside the scope of the class, but these private members can only be accessed with the help of public methods of the same class.
- public specifier : This keyword allows the data and function(s) as public interface which can be accessed within the class itself as well as outside the scope of the class or sub-class.
- protected specifier : This keyword converts the members (data and function(s)) in protected mode, so the protected members can be accessed through either its own class or by the subclass.
4. Differentiate between private and protected visibility modifiers.
Ans. private members are accessible only in the class in which they have been defined. Protected members are accessible in the class in which they have been defined as well in the sub classes of that class.
5. How are private members of a class different from public members?
Ans. Private members of a class can be accessed only by the methods of the class in which they are declared. While public members can be accessed outside of the class also.
6. What are member variables? State their types?
Ans:
- Member variables are also known as Instance variables.
- These member variables are used to store value in the class.
- It may be public, private and protected, where private and protected members remains hidden from outside world and there by support data.
7. Define the term Local variable and Global variable?
Ans: Local Variable: Variable declared inside a method or block.
Global Variable: Class variable which is available to the entire class.
8. What is class variable? Give an example?
Ans.
- Class variables are those variables which are initialized inside the class and outside of all of the blocks with static prefix.
- The scope of a class variable is throughout the class in which that variable is declared.
- Class variables support access specifiers.
class Example{ public static int x; //Class Variable static int num; //Class Variable Void method1(){ //statements.. } public static void main(){ //statements. } }