Singleton Object in Java and Scala

Table of contents
Reading Time: 2 minutes

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:

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

compile the above programme the ouput screen some thing look like this:
marks are=88
grade A
marks are=88
grade A
true
“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

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.

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

now called Demo.show()

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading