Core java interview Questions You'll Most Likely Be Asked (Second Edition)


What is the best practice in declaring instance variables?


Download 1.52 Mb.
Pdf ko'rish
bet7/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   2   3   4   5   6   7   8   9   10   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

What is the best practice in declaring instance variables?
Answer:
Instance variable should always be declared as private. They
should have public getter/setter methods. This helps to protect
the instance variable as they can only be modified under the
programmer’s control. This is as per the Encapsulation principle.
Declaring instance variables as public violates the encapsulation
principle and poses a security issue. Public instance variables
can be maliciously modified outside your class. If at all an
instance variable needs to be accessed from a sub–class, it can
be made protected.
What is a singleton class?
Answer:
A class which lets you create only one instance at any given time
is termed a Singleton class. A Singleton class can be
implemented via a private constructor and a public getter method.
The following code demonstrates this.
public class MySingleton {
private static MySingleton mySingletonInstance;
private MySingleton () {
}
public static MySingleton getInstance () {
if (mySingletonInstance == null) {


007.
mySingletonInstance = new MySingleton (); //
create the object only if it is null
}
return mySingletonInstance;
}
public void doSomething () {
System.out.println(“I am here....”);
}
public static void main(String a[]) {
MySingleton mySingleton =
MySingleton.getInstance();
mySingleton.doSomething();
}
}
Here, a private constructor and a public getInstance method is
defined. The getInstance checks if an instance exists. If an
instance does not exist, it creates one using the private
constructor. If an instance exists, it just returns it. Any external
class that needs an instance of the Singleton class, needs to
obtain it via the getInstance method. The getInstance
method ensures that there is only one instance of the Singleton
class.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   2   3   4   5   6   7   8   9   10   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling