When I was learning Scala today, I suddenly wanted to use idea to create a learning class (the CMD code was too painful) to create a class directly:
Class Test {
def main (args:array[string]) {
print ("Hello world!")
}
}
When I want to run this main function, the lack of execution, then depressed, again look at the new, just know, Scala class classification:
What's the difference between the three types: Class,object,trait?
Class
In Scala, the class name can be the same name as the object name, which is called the associated object of the class, and the classes and associated objects can access their private properties, but they must be within the same source file. The class is only compiled, cannot be executed directly, the declaration of the class is declared with the main constructor, and in a class, the primary constructor has only one secondary constructor that must declare the main constructor internally or other declaration of the main constructor, and the main constructor executes all the statements in the class definition. Scala provides getter and setter methods for each field, as well as declarations that can be displayed, but for the Val type, only the Getter method is provided, by default the field is public, and you can add a restriction to the setter method to limit the variable range. Methods in Scala can access private fields of all objects in the class
Object
There are no static and static fields in Scala, so it is possible to use object in Scala to implement these functions, and methods called directly with object names are implemented in this way, such as array.tostring. The constructor of the object is called when it is first used, and if an object is never used, then his constructor is not executed, and the object essentially owns all the attributes of the class (Scala), and in addition to it, an extension class and one or more attributes are possible: for example,
Abstract class ClassName (val parameter) {}
Object Test extends ClassName (val parameter) {}
Note: Object cannot provide constructor arguments, which means that object must be an argument-free
Trait
Multiple inheritance can be implemented through interface in Java, and multiple inheritance can be achieved through feature (trait) in Scala, but unlike Java, it can define its own properties and implementation method body, which can be considered when it is not in its own implementation method. Interface is equivalent, and in Scala it is generally only possible to inherit one parent class, which can be multiple-inheritance with more than one with.
Trait traita{}
Trait traitb{}
Trait traitc{}
Object Test1 extends Traita with TRAITB with traitc{}