Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

static / singleton

  Asked By: Sunil    Date: Feb 15    Category: Java    Views: 677
  

i just want to share you what i've learned today.

import java.io.*;
import java.lang.*;

public class singleton
{
static class single_obj
{
static int object = 24;

void inc()
{
object++;
}

void dec()
{
object--;
}


int value()
{
return object;
}
}



public static void main(String args[])
{
System.out.println("\nstatic objects\n");
System.out.println("initial value of object is 24\n");

single_obj instance_1 = new single_obj();
System.out.println("\n\nthe initial value of 1st instance is " +
instance_1.value());
instance_1.inc();
System.out.println("incremented value of 1st instance is " +
instance_1.value());

single_obj instance_2 = new single_obj();
System.out.println("\n\nthe initial value of 2nd instance is " +
instance_2.value());
instance_2.inc();
System.out.println("incremented value of 2nd instance is " +
instance_2.value());

single_obj instance_3 = new single_obj();
System.out.println("\n\nthe initial value of 3rd instance is " +
instance_3.value));
instance_3.dec();
System.out.println("decremented value of 3rd instance is " +
instance_3.value());


System.out.println("\n\n");


}
}

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Al Allen     Answered On: Feb 15

Would like know more knowledge on this ..if any can ..

for making a file singleton  , we have to make the constructr static  or
method statis..

in the below e.g.

public class  singleton
{
static class single_obj

singleton class is having single_obj class inside it..is it possible in
JAVA ??

any idea on this ?? ?

 
Answer #2    Answered By: Viola Hanson     Answered On: Feb 15

public class  MySingleton {

private static  MySingleton me = new MySingleton();

private MySingleton() {
// do something if you want
}

public static MySingleton getInstance() {
return me;
}

public void  doSomething() {
System.out.println("I am a stupid method");
}
}

This implementation is considered thread safe.

 
Didn't find what you were looking for? Find more on static / singleton Or get search suggestion and latest updates.




Tagged: