1. Class
Scala classes are a bit different from classes in C #, such as declaring a field that is not priavate decorated var age,scala compiler field helps us to produce a private field and 2 public method get and set, which is similar to C # 's simple properties; If you use the private adornment , its methods will also be private. This is the so-called unified access principle.
[Java]View Plaincopy print?
- Class is the public level by default
- Class person{
- var age= //field must be initialized ()
- def age=age //This is the method, no parameters can be omitted ()
- Def incremen () {this.age+=1}
- }
- Class student{
- var age= ///The underlying compiler automatically adds a public method of get and set to the private age, which can be understood as pseudo type
- private[this] var gender="male" //private[this] only this class can use the
- Private var name="Clow" //declares private, the underlying compiler automatically adds the get and set proprietary methods for the private name
- //But you can define your own property methods
- def getname=THIS.name
- def setName (value:string) {This.name=value}
- }
- Use of constructors
- Class Teacher {
- var Age:int = _
- var name:string = _ //Can be reserved
- //Overloaded constructors are similar to the public Teacher () {} inside C #
- def this (Age:int, name:string) {
- This () //must be called once for the main constructor
- This.age=age
- This.name=name
- }
- }
2, Scala does not have static modifiers, but the members under object are static, if there is a class with the same name, this is its associated class. In object, you can generally do some initialization for the associated class, such as the Val Array=array (PS: It uses the Apply method) that we often use
[Java]View Plaincopy print?
- Object dog{
- private var age=0
- def age={
- age+=1
- Age
- }
- }
- Class dog{
- var age1=dog.age //dog.age is a private field of object Dog. It reminds me of the friend class of C + + .
- }
3, how to explain the use of apply? Let's see how we can use it to implement a singleton pattern.
[Java]View Plaincopy print?
- Class Applytest private{ //Add private hidden constructor
- Def SayHello () {
- println ("Hello Jop")
- }
- }
- Object applytest{
- var instant:applytest=Null
- def apply () ={
- if (instant==null) instant=new applytest
- Instant
- }
- }
- Object Applydemo {
- def main (args:array[string]) {
- Val T=applytest ()
- T.sayhello ()
- }
- }
The difference between class and object in Scala