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


Please Help Members By Posting Answers For Below Questions

What is array command?

823


How does hashset work in java?

823


How do you insert a line break?

704


How do you sort in descending order in java using collections sort?

715


What’s the difference between constructors and other methods?

769


Is nan false?

737


What is a double vs float?

761


Can we define package statement after import statement in java?

789


What is casting in java programming?

788


What is difference between final and finally in java?

835


Is string pool garbage collected?

782


What are parsers? Dom vs sax parser.

806


What is the function of character?

793


Which is faster string or stringbuilder?

724


What are the different types of garbage collectors in java?

831