Scala: the difference between the Object and Class

1. Declare private variables in Scala, Scala compiler automatically generates get, set method
2. In Scala variables need to be initialized
3. There is no static modifier in Scala, all members in the object are static, if at It declared the object class with the same name of the class is the object class "associated object", so for a class, all the member variables and methods before the new instance is not accessible it is
to be understood as Scala focused on the class static objects into the object, the companion object and class files must be the same source file, you can do some initialization operations associated with the object.
4. the interface can be achieved through multiple inheritance in Java, can in Scala achieved through multiple inheritance feature (trait), but unlike Java, it can define your own properties and methods to achieve body
5.object not provide a constructor argument, that object must be no arguments

Scala difference in the class of object
in Scala, the class name and the object can be called the same name, the object is called companion object of the class, class and associated objects can access their private property each other, but they must be in the same source file

class


 

scala in class: the compiler will automatically help us produce a private field and two public methods get and set
the class will be compiled, not directly enforceable, and declare the class with the main constructor is declared in a class, the main only a constructor.
class and its companion object can access each of its private members, main method in the class of no use

object


 

scala in object: all the member variables and methods are static by default, so you can directly access the main method

One difference is that class and object, singleton object with no parameters, and class. Because you can not instantiate a singleton object using the new keyword, you have no chance to pass parameters to it

class Lis {
  var age=19
}
object Test{
  def main(args: Array[String]): Unit = {
    var s=new Lis
    s.age=10    //set
    println(s.age)  //get
  }
}

 

Guess you like

Origin www.cnblogs.com/AlanWilliamWalker/p/10959055.html