Scala Advanced __scala

Source: Internet
Author: User
Tags anonymous control characters
Scala Advanced Defining Classes
Class user{

  //Members must be first made,
  var name:string=null

  @BeanProperty var alias:string= "Caspar"

  Private[this] var age=null

  //println will be part of the main builder and executed
  println ("Constructing user ...")

  //Rewrite ToString () method when creating objects
  override Def toString () = name + ":" + Alias

}

By inheriting the app, defining an Application object
//Extension app, the program can run directly without having to define the main method itself, and the code is more concise
object Usertest extends app{
  var user = New User ()
  user.name= "Caspar"//direct modification, but actually calls p.name_= ("Jonh")
  user.alias_= ("CSP") println ( 
  User)
}

*scala will generate name () by default, name_= (.) and Constructors ()
*name () corresponds to the GetName () method in Java
*name_= () corresponds to the SetName () method in Java
* Defined is a public member, but generated bytecode is implemented in a private manner, the generated Getter,setter method is common
* Define private members, their getter,setter is also private
* If the member field is defined as Private[this], the Getter,setter method is not generated
*private[this] can only be accessed by objects created by the class itself, so the class members that it defines are also called object private members
* If you need to automatically generate Getter,setter methods like in Java, you need to refer to Scala.reflect.BeanProperty and modify the variables in annotations
* When the parameters of the main constructor are not modified with Var or val, the parameters generate the private Val members of the class and do not produce getter and setter methods


Customizing Getter and Setter Methods

def name=name  
def name_= (name:string) {  
    this.name=name
}


Define the primary constructor while defining the class

Class User (Val name:string,val age:int) {
  override def tostring:string = name + ":" + Age
}

object Test extends app{
  val user = new User ("Caspar",)
  println (user)
}


Main builder with default parameters


Parameter with access control in main constructor

Class User (Val name:string,private val age:int=19) {
  override def tostring:string = name + ': ' + Age
  println (' age ' + Age)
}

Object Test extends app{
  val user = new User ("Caspar",)
  //user.age//error
  Inaccessible println (user)
}


The class name is followed by the private keyword to make the main builder private and not allow external use


* If you disable the main builder, you must use the auxiliary constructor to create the object
* The name of the secondary builder is the same as the class name in the This,java, which often results in a number of problems when modifying the class name, which is avoided by the Scala language
* When calling an auxiliary constructor, you must first call the primary constructor or other already defined constructors

Classes with only auxiliary constructors

Class User () {//member private Var name:string=null private var age:int=18 private var
  sex:int=0

  / Auxiliary builder
  def this (name:string) {This
    ()
    this.name=name
  }
  def (name:string,age:int) {
    This (name)
    This.age=age
  }
  def this (name:string,age:int,sex:int) {This
    (name,age)
    This.sex=sex
  }
  override def tostring:string = name+ ": +age+": "+sex
}

object Test extends app{
  val user1 = new User ("Caspar", 12,1)
  val user2 = new User ("Caspar",)
  val user3 = new User ("Caspar")
  println (user1)
  println (user2)
  println (User3)
}

Classes with primary and secondary constructors

Class User (var name:string,var age:int) {
  //class member
  private var sex:int=0

  def this (name:string,age:int,sex:i NT) {This
    (name,age)
    this.sex=sex
  }
  override def tostring:string = name + ": +age+": "+sex
}

" Object Test extends app{
  val user1 = new User ("Caspar", 12,1)
  val user2 = new User ("Caspar",)
  println (User 1)
  println (user2)
}


Abstract class

An abstract class is a class that cannot be instantiated, and an abstract class that includes an abstract method that is not implemented, which extends its implementation by subclasses
Subclasses inherit abstract classes, methods in an abstract class must have implementations, or subclasses must also be defined as abstract classes
An abstract class can also directly new an anonymous class object that implements the method in the Anonymous class object

Abstract class definitions in Scala

Abstract class User {
  def login:unit
}

In addition to abstract methods, you can have abstract fields in an abstract class:

abstract class User {def login:unit//abstract field, the definition field in the generic class must be initialized, but not in the abstract class this requires Var age:int var Name:strin G}//The name parameter is initialized with the main constructor class waiter (Var name:string) extends user{override def Login:unit = {println ("Waiter 
  ' +name+ ' is logined '} override var Age:int = _} class Customer extends user{//implementation of methods in the parent class, note that you can not add the override keyword def login:unit = {println ("Customer" +name+ "is Logined")} override var Age:int = 0 override var name:s Tring = null} object Test extends app{val user = new Customer () User.Name = "Caspar" User.login val waiter = n EW Waiter ("Caspar") Waiter.login//The following code defines an anonymous class, and instantiates//Direct new User, followed by the contents of the class//user is an abstract class, it is not instantiated//here can The direct new operation is sufficient because we have extended the User class, which is anonymous and can only use one time var somebody = new User {override def Login:unit = {println ("User" +na Me+ "is Logined")} override var name:string = _ override var Age:int = _} somebody.name= "Caspar" som Ebody.login} 
associated objects with associated classes
Class User {
  def print:unit ={
    usertest.num+=1
    println (
      usertest.num+) \tname: "+name+" \tage: "+age"
  }
  var Age:int = _
  var name:string = _
}

Object Usertest extends app{
  var num = 0
  var user = new User ()
  user.name= "Caspar"
  user.age=29
  user.print
  user.print
  user.print
}

Object Usertest is referred to as the associated object of class user, while class user is called the companion class of Object Usertest
Inner class

* An inner class can access the private members of an external class like other members of a class * External classes cannot access member domains of internal classes, but internal classes can directly access external class member fields, even if private

Class User {
  def print:unit ={
    println (
      "Name: +name+" \tage: "+age)
  }
  var name:string = _
  private var pwd:string = "Password"
  var age:int=18

  private[this] def info:string = "Name:" +name+ "\tage:" +age
  class Socialaccount (var google:string) {
    var qq:string = _
    var email:string = _
    var facebook:string= _< c12/>//internal classes can directly access the member variables and member methods of the external class, even if the private
    override def tostring:string = info+ "\tpwd: +pwd+" \TQQ: "+qq+" \ Temail: "+email+" \tfacebook: "+facebook+" \tgoogle "+google
    def print:unit ={println
      (This)
    }

  }
}

Object Test extends app{
  val user = new user
  user.name= "Caspar"
  user.age=19
  user.print
  var a = New user. Socialaccount ("Google account")
  a.facebook= "The Facebook account
  " a.qq= "the QQ account"
  a.email= " Test@test.com "
  a.print
}"
inheritance extends and polymorphism of class

* "Polymorphism" (polymorphic) is also called Dynamic Binding, "late binding" (Late Binding), which refers to the actual type of the object being referenced during execution (not during compilation), and its corresponding method is invoked based on its actual type. "means that a reference to a subclass can be assigned to a parent class, and the program invokes the corresponding method at run time based on the actual type
*override method rewriting refers to the way in which subclasses override the parent class when subclasses inherit the parent class, and method overrides are the key to implementing polymorphism and dynamic binding
The method in *scala is the same as Java, and it is an algorithm that rewrites the parent class using the Override keyword identifier
Inheritance of Classes

Class User {
  def print:unit ={
    println (
      "Name: +name+" \tage: "+age)
  }
  var name:string = _
  private var pwd:string = "Password"
  protected var phone:string = "12345678900"
  var age:int=18
}

Class The Customer (var vip:boolean) extends user{
  //subclass can access the protected properties and methods of the parent class, but cannot access private properties and methods

  //overrides its own implementation
  Override Def Print:unit = println ("Customer name: +name+" \tcustomer Age: "+age+" \TVIP: "+vip+" \tphone: "+phone"}<)
The reference to the C15/>object Test extends app{
  //user class can point to any subclass of the User class
  val c:user = new Customer (false)
  C.name= "Caspar "
  c.age=19
  //c.phone =10  Here cannot access protected phone
  C.print/The program will call the print () method
in the corresponding different subclasses according to the actual type }
Constructor Execution Order
Class User {
  println ("First line output: User ...")


  def print:unit ={
    println (
      "Name:" +name+ "\tage:" +age)
  var name:string = _
  private var pwd:string = "Password"
  protected var phone:string = "12345678900"
  var A Ge:int=18
}

class Customer (var vip:boolean) extends user{
  var qq:string = _
  var email:string = _
  def this (vip:boolean,qq:string,email:string) {This
    (VIP)
    this.qq = QQ
    this.email = Email
    println ("Second line output: Customer this" (...)

  println ("Third line output: Customer ...")

  //subclass can access the protected properties and methods of the parent class, but cannot access private properties and methods
  override def print:unit = println ("line fourth output: Customer name:" +name+ "\tcustomer Age:" +age+ "\TVIP:" +vip+ "\tphone:" +phone)
}

Object Test extends app{
  val c:user = new Customer (False, "q1234677", "email@test.com")
  c.name= "Caspar"
  c.age=19
  //c.phone =10  No access to protected phone
  c.print
}
Trait

Scala, like the Java language, uses a strong restrictive strategy to avoid multiple inheritance problems. In the Java language, only one superclass is allowed, which can implement multiple interfaces, but the Java interface has its own limitations: an interface can only include abstract methods, cannot contain fields, concrete methods. &NBSP
Scala uses trait to solve the problem, and in Scala's trait it can include not only abstract methods but also fields and concrete methods. &NBSP
Use with to implement trait interface  
trait with implementation   with specific fields and specific methods;
trait has its own constructor, which is an parameterless constructor, and cannot define the trait constructor with parameters   The construction order of the

trait  
1. If a superclass is available, the constructor   for the superclass is invoked first, and
2. If there is a parent trait, it invokes the constructor trait of the parent   in accordance with the inheritance hierarchy;
2. If there are multiple parent trait, the   is executed sequentially from left to right;
3. This class is constructed only after all parent constructors and parent trait are constructed  

Trait User {
  //define an abstract method, note that you do not need to add abstract
  def login (id:string): String
  def Add (o:any): Boolean
  def Update (O:any): Int
  def query (id:string): List[any]
}

trait Vip {
  def info (vip:boolean): Boolean
  / /with specific fields
  private var num = 0
  
  //implementation
  def upgrade={num+=1 println with specific methods and
    attributes
    ("Upgrade to" +num+ VIP member)
  }
}

Class Customer extends User with vip{
  override def login (id:string) =id

  override def Add (o:any): Boolean = {
  if (O==null) False
    else true
  }

  override def update (o:any): Int = {
    if (o==null) 0
    Else 1
  }

  Override def query (id:string): List[any] = List (ID, "AAA", "BBB")

  override def info (vip:boolean): Boolean = VIP
}

Object Test extends app{
  val u = new Customer
  predef println u.login ("userid 001")
  println (U.add (" Add User "))
  println (u.update (" Update User "))
  println ((u query" userid 001 "). Mkstring (", "))
  println (" VIP: "+u.info (false))
  U.upgrade
  U.upgrade
}
self Type (=>)

Use a

Class Outerclass { 
    outer =>//defines an external class name
    val v1 = "Here"
    class Innerclass {
        ///with outer to represent external classes, Equivalent to Outerclass.this
        println (outer.v1) 
    }
}

Use a

Trait User {
  //define an abstract method, note that you do not need to add abstract
  def login (id:string): String
}

class customer{
  //self: User => requires the customer to instantiate or define a subclass of the customer
  //must mingle with the specified user trait, and this user type can also be specified as the current type
  self:user=>
} //

class Test expands the customer must be mixed with trait User
//Otherwise will be the error
Object test extends customer with user{
  override def login (id:string): String = id+ "Login ..."

  def main (args:array[string]): unit = {
    println (login ("001")) 
  }
}
Package Object

Package objects are used primarily to refer to constants, tool functions, using the package name directly
Definition of package Object

Package Com.scala.test

Define a single Instance object with the Package keyword

Package Object id{
  var id=0
  def autoincrementid:int={
    id+=1
    Id
  }
}

object Test extends app{
  println (id.autoincrementid)
  println (Id.autoincrementid)
  println (Id.autoincrementid)
}
Access Control

In the Java language, the access control of a class member in a package is implemented primarily through public, private, protected, and default controls, and when a class is defined, if the class member does not add any access control characters, the class member is visible in the package that defines the class. There is no public keyword in Scala, only private and protected access control characters, and when a class member does not add private and protected, its access rights are public. The following is explained individually:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.