what is the difference between static class and singleton class? can we create static class?
Answer Posted / pratima thakur
1.We can create static class object like the below example.
class OuterClass
{
void outerMethod()
{
System.out.println("Inside in outerclass");
}
static class InnerClass
{
void innerMethod()
{
System.out.println("Inside in innerclass");
}
}
public static void main(String args[])
{
InnerClass iclass=new InnerClass();
InnerClass iclass1=new InnerClass();
iclass.innerMethod();
}
}
2.Single tone class implementaion
public class MySingleTon {
private static MySingleTon myObj;
/**
* Create private constructor
*/
MySingleTon(){
}
/**
* Create a static method to get instance.
*/
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
public void getSomeThing(){
// do something here
System.out.println("I am here....");
}
public static void main(String a[]){
MySingleTon st = MySingleTon.getInstance();
System.out.println(st);
MySingleTon st1 = MySingleTon.getInstance();
System.out.println(st1);
st.getSomeThing();
}
}
| Is This Answer Correct ? | 1 Yes | 0 No |
Post New Answer View All Answers
What is string buffer?
Why packages are used?
What is final access modifier in java?
What are the different types of sorting in java?
What are the differences between Java 1.0 and Java 2.0?
How we can execute any code even before main method?
What is difference between iterator and enumeration in java?
Is node a data type in java?
What is an immutable object? How do you create one in java?
What are "methods" and "fields"?
What is a method vs function?
Write code to implement bubble sort in java?
What about static nested classes in java?
What is the difference between path and classpath variables?
Is it possible to use string in the switch case?