Scala: Singleton and Companion Class

Hi,

In this blog i wil write a program which will explain the concepts of singleton object and companion class , please read the comments of programm which will explain the code line

following is the code :-
// singleton objects which are of single time use as we can not instantiate them
// companion class is a class which share same name as singleton object
// singleton object and class can exchange the variables and method values between them as shown below

object singleton{
private val num=10 // declare private value for particular object

def show()
{
var obj=new singleton // create object of companion class , this is must
println(“value of variable num is :” + obj.num2) // access the variable of companion class
}

}

class singleton { // creation of companion class share same name as singleton object
import singleton._ // must stem a kind of linkage between class and object

private val num2= 13;
def newshow()
{
println(“value of companion class variable num is : ” + num) // access variable value imp :- variable is private

}
}

object main
{
def main(args:Array[String])
{
var ob = new singleton // object of companion class
ob.newshow() // access newshow method
singleton.show() // acess show() method

}

}

 

Outpur will be as follows :

value of companion class variable num is : 10
value of variable num is :13

 

 

Please like , comment and share .

 

Thanks  .. cheers

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s