This Tutorial is helpful to  create singleton object.This tutorial shows the difference between the JAVA singleton and SCALA singleton object .First we start with Java

Singleton object:- The purpose of singleton object is to control object creation, limiting the number of obejcts to one only.This is useful when exactly one object is needed to coordinate actions across the system.

A simple java programme to create singleton object:

Class Student
 * static Student stobject;
 int marks;
 private Student()
 private Student( int marks)
 void show()
 System.out.println("marks are = " + marks);
 System.out.println(" grade A");
 else if (marks >= 60)
 System.out.println(" grade B");
 static Student createObject(int x)
 stobject=new Student(x);

Now make class to create the object of the Student class. Suppose the class name is Demo

Class Demo
 public static void main(String str[]) {
 Student st_object_1 = Student.createObject(88);
 Student st_object_2 = Student.createObject(66);;;
 System.out.println(st_object_1 == st_object_2)

compile the above programme the ouput screen some thing look like this:
marks are=88
grade A
marks are=88
grade A
“Here we can not get the second object refrence id , the object st_object_2 also refer to same refernce id of st_object_1 if we compare st_object_1 and st_object_2 it print true”

NOTE:-this programme is not successfully create the singleton object. We can break it . This is showing below

public static void main(String str[])
 Student st_object_1 = Student.createObject(88);;
 Student.stobject = null;
 Student st_object_2 = Student.createObject(66);;

to make the singleton object we make static variable of class Student (stobject) Private so that we can not access it outside the Student class.

* private static Student stobject;

Now we achieve the singleton object successfully in java.

If we talking about Scala , Scala is more object-oriented than Java because in Scala we cannot have static members It has singleton objects instead.

Syntactically it looks like a class, except you use the keyword object

object Demo {
 val marks=80
 def show(){
 println("marks are = " + marks)
 println(" grade A")
 else if (marks >= 60)
 println(" grade B")

now called

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s