0

I am learning scala. I have one basic question.

My question is not about class. It is about objects.

I would like to understand how scala's class instance differs from java class instance.

I have the below code in scala

class Employee(var id:Int,var name:String)
{

    def show()
    {
      println("Id : " +id)
      println("Name :"+name)
    }

}

 object obj1
 {
     def main(args: Array[String])
     {
         val emp1 = new Employee(100,"Surender")
         emp1.show
     }
 }

I want to know what is obj1? Can we say obj1 is the instance of class Employee or object of class Employee.

Similarly How does Obj1 differ from emp1?

Surender Raja
  • 3,553
  • 8
  • 44
  • 80
  • 1
    Possible duplicate of [Difference between object and class in Scala](http://stackoverflow.com/questions/1755345/difference-between-object-and-class-in-scala) – baudo2048 Jun 05 '16 at 18:13

2 Answers2

0

Obj1 is not instance of any named class. It is a single instance on an (implicit constructed by scala) anonymous (inaccessible) class. I think you cannot say that obj1 is instance of Employee. So obj1 is an instance of an anonymous class, and emp1 is an instance of Employee class.

baudo2048
  • 1,132
  • 2
  • 14
  • 27
0

object is a shorthand for defining a type and instantiating it in a single declaration. The type of obj1 is obj1.type (you can see this by entering :t obj1 into the REPL).

Can we say obj1 is the instance of class Employee or object of class Employee.

No, there is no relationship between Employee and obj1.

How does Obj1 differ from emp1?

They're totally different things. A more apt question would be "what does obj1 have in common with emp1?", to which the answer is merely that they share the common ancestor java.lang.Object, as all references do.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
  • They can also access each other's private fields, like here: http://stackoverflow.com/a/1755942/4496364. – insan-e Jun 05 '16 at 21:13
  • @insan-e, no, it needs to be a companion object for that. That's not the case in the this question. – pedrofurla Jun 06 '16 at 02:45