object

object amount to class A single instance of , Usually put some static field perhaps method; stay Scala There are no static methods and static fields in , But you can use object This grammatical structure to achieve the same goal .
object effect :

  • 1. Store tool methods and constants
  • 2. Efficiently share a single immutable instance
  • 3. The singleton pattern
package com.zy.scala.cls
class Session {}
object SessionFactory {
// This part is equivalent to java Static blocks in
val session = new Session // stay object The method in is equivalent to java Static methods in
def getSession(): Session = {
session
}
} object SingletonDemo {
def main(args: Array[String]) {
// Singleton object , Unwanted new, use 【 Singleton object name . Method 】 Call method in object
val session1 = SessionFactory.getSession()
println(session1)
// Singleton object , Unwanted new, use 【 Singleton object name . Variable 】 Call a member variable in an object
val session2 = SessionFactory.session
println(session2)
}
}

Companion

If there is a class file , There's another one with class Homonymous object file , Then call this object yes class The companion of ,class yes object Associated with ; The companion class and object must be stored in one .scala In file ; The most important feature of associated class and associated object is , Can visit each other .

package com.zy.scala.cls
// Companion class 
class Dog {
val id = 1
private var name = "itcast" def printName(): Unit = {
// stay Dog Class can access accompanying objects Dog Private property of
println(Dog.CONSTANT + name)
}
} // Companion
object Dog {
// Private properties in accompanying objects
private val CONSTANT = " Wang Wang Wang : " def main(args: Array[String]) {
val p = new Dog
// Access private fields name
p.name = "123"
p.printName()
}
}

Scala Medium apply Method

object It's a very important special method in , Namely apply Method ;

apply Methods are usually implemented in accompanying objects , Its purpose is to , Through the constructor function of the accompanying class , To implement the constructor function of the associated object ;
Usually we define... In the companion object of the class apply Method , When you meet a class name ( Parameters 1,... Parameters n) when apply Method will be called ;
When creating objects of accompanying objects or classes , It's not usually used new class/class() The way , But directly class(), Implicitly call the... Of the accompanying object apply Method , This makes the creation of objects simpler ;

package com.zy.scala.cls
/**
* Array Class , It can receive variable length parameters apply Method ,
* And by creating a Array Class , The function of constructor of associated object is realized
*/
// Appoint T Data types of generics , And use the variable length parameter xs Receive and transmit parameters , return Array[T] Array
// adopt new Keyword creation xs.length Long Array Array
// In fact, it's called Array Associated with constructor Conduct Array Object initialization
// def apply[T: ClassTag](xs: T*): Array[T] = {
// val array = new Array[T](xs.length)
// var i = 0
// for (x <- xs.iterator) { array(i) = x; i += 1 }
// array
// }
object ApplyDemo {
def main(args: Array[String]) {
// Called Array Accompanied by apply Method
//def apply(x: Int, xs: Int*): Array[Int]
//arr1 There is only one element in 5
val arr1 = Array(5)
//new A length of 5 Of array, The array contains 5 individual null
var arr2 = new Array(5)
println(arr1.toBuffer)
}
}

Inherit

Scala in , Let the child class inherit the parent class , And Java equally , Is also used extends keyword ;

Inheritance means , A subclass can inherit from a parent field and method , Then the subclass can also implement what the parent class doesn't have inside itself , Subclass specific field and method, Using inheritance can effectively reuse code ;

A subclass can override the parent's field and method, But if the parent class uses final modification , perhaps field and method use final modification , Then the class cannot be inherited , perhaps field and method It can't be covered .

private Embellished field and method Cannot be inherited by subclasses , Can only be used inside a class ;

field It has to be defined as val Only in this way can it be inherited , And use override keyword . because var Embellished field Is variable , It can be directly referenced in subclasses , No need to be inherited ; namely val Modification is allowed to be inherited ,var Modified is only allowed to be referenced . Inheritance is change 、 Cover means .

Java Access control rights in , The same applies Scala

Intra class

This package

Subclass

External package

public

protected

×

default

×

×

private

×

×

×

package com.zy.scala.extends_demo
class Person {
val name = "super" def getName = this.name
} class Student extends Person {
// Inheritance plus keywords
override
val name = "sub"
// Subclasses can define their own field and method
val score = "A" def getScore = this.score
}

Scala in override and super keyword

  • Scala in , If the subclass wants to override a non abstract method in the parent class , You have to use override keyword ; A subclass can override the parent's val Embellished field, Just use... In subclasses override Key words can be used .
  • override Keywords can help developers find errors in code as early as possible , such as , override The method name of the modified parent method is misspelled .
  • Besides , After the subclass covers the parent method , If you want to call the overridden method in the parent class in the subclass , You have to use super keyword , The display indicates the parent class method to call .
package com.zy.scala.extends_demo
class Person1 {
private val name = "leo"
val age = 50 def getName = this.name
} class Student extends Person1 {
private val score = "A"
// A subclass can override the parent's val field, Use override keyword
override
val age = 30 def getScore = this.score // Override parent non abstract methods , You have to use override keyword
// Call the method of the parent class at the same time , Use super keyword
override def getName = "your name is " + super.getName
}

Scala in isInstanceOf and asInstanceOf

If you instantiate a subclass object , But give it to a variable of the parent type , In the following process , You also need to convert the variables of the parent type to the variables of the child type , How to do ?

  • First , Need to use isInstanceOf Determine whether the object is an object of the specified class , If so , You can use asInstanceOf Convert object to specified type ;
  • Be careful : p.isInstanceOf[XX] Judge p Is it XX Instance of object ;p.asInstanceOf[XX] hold p convert to XX Instance of object
  • Be careful : If it doesn't work isInstanceOf First, judge whether the object is an instance of the specified class , Use directly asInstanceOf transformation , An exception may be thrown ;
  • Be careful : If the object is null, be isInstanceOf Be sure to return false, asInstanceOf Be sure to return null;
  • Scala And Java Type checking and conversion

Scala

Java

obj.isInstanceOf[C]

obj instanceof C

obj.asInstanceOf[C]

(C)obj

classOf[C]

C.class

package com.zy.scala.extends_demo
class Person3 {}
class Student3 extends Person3
object Student3 {
def main(args: Array[String]) {
val p: Person3 = new Student3
var s: Student3 = null
// If the object is null, be isInstanceOf Be sure to return false
println(s.isInstanceOf[Student3])
// Judge p Is it Student3 Instance of object
if (p.isInstanceOf[Student3]) {
// hold p convert to Student3 Instance of object
s = p.asInstanceOf[Student3]
}
println(s.isInstanceOf[Student3])
}
}

Scala in getClass and classOf

  • isInstanceOf Can only determine whether the object is the object of the specified class and its subclass , And can't accurately judge , Object is the object of the specified class ;
  • If you want to accurately determine that the object is the object of the specified class , Then you can only use getClass and classOf 了 ;
  • p.getClass You can get the class of the object exactly ,classOf[XX] You can get the class exactly , And then use == Operator can judge ;
package com.zy.scala.extends_demo
class Person4 {}
class Student4 extends Person4
object Student4 {
def main(args: Array[String]) {
val p: Person4 = new Student4
// Judge p Is it Person4 Class
println(p.isInstanceOf[Person4]) //true
// Judge p Is the type of Person4 class
println(p.getClass == classOf[Person4]) //false
// Judge p Is the type of Student4 class
println(p.getClass == classOf[Student4]) //true
}
}

Scala Pattern matching is used in pattern matching for type judgment

  • In actual development , such as spark Source code , A lot of places use the syntax of pattern matching to judge the type , This way is more concise , And the maintainability and extensibility of the code are also very high ;
  • Use pattern matching , Functionally , And isInstanceOf It does the same thing , It mainly determines whether it is the object of this class or its subclass , It's not accurate judgment .
  • Equate to Java Medium switch case grammar ;
package com.zy.scala.extends_demo
class Person5 {}
class Student5 extends Person5
object Student5 {
def main(args: Array[String]) {
val p: Person5 = new Student5
p match {
// Is the match Person Class or its subclass object
case per: Person5 => println("This is a Person5's Object!")
// Match all the rest
case _ => println("Unknown type!")
}
}
}

Scala in protected

  • Follow Java equally ,Scala You can also use protected Keyword to decorate field and method. In a subclass , You can directly access the field and method, Instead of using super keyword ;
  • You can also use protected[this] keyword , The scope of access protection : Access to the parent class's is only allowed in the current subclass field and method, Access to the parent class's through other subclass objects is not allowed field and method.
package com.zy.scala.extends_demo
class Person6 {
protected var name: String = "tom"
protected[this] var hobby: String = "game" protected def sayBye = println(" bye ...")
} class Student6 extends Person6 {
// The parent class uses protected Keyword to decorate field You can directly access
def sayHello = println("Hello " + name) // The parent class uses protected Keyword to decorate method You can directly access
def sayByeBye = sayBye def makeFriends(s: Student6) = {
println("My hobby is " + hobby + ", your hobby is UnKnown")
}
} object Student6 {
def main(args: Array[String]) {
val s: Student6 = new Student6
s.sayHello
s.makeFriends(s)
s.sayByeBye
}
}

Scala The parent class is called constructor

  • Scala in , Each class can have a master constructor And any number of AIDS constructor, And every auxiliary constructor The first line of must call other auxiliary constructor Or the Lord constructor Code ; So subclass assistance constructor It is impossible to call the parent class directly constructor Of ;
  • Only in the subclass of the main constructor The parent class is called constructor.
  • If the constructor of the parent class has been defined field, such as name and age, When subclasses are reused , Don't use val or var To embellish , Otherwise it will be considered , The subclass should cover the parent class field, And must use override keyword .
package com.zy.scala.extends_demo
class Person7(val name: String, val age: Int) {
var score: Double = 0.0
var address: String = "beijing" def this(name: String, score: Double) = {
// Every auxiliary constructor The first line of must call other auxiliary constructor Or the Lord constructor Code
// Lord constructor Code
this(name, 30)
this.score = score
} // Other AIDS constructor
def this(name: String, address: String) = {
this(name, 100.0)
this.address = address
}
} class Student7(name: String, score: Double) extends Person7(name, score)

Scala Anonymous inner classes in

  • stay Scala in , Anonymous inner classes are very common , And it's powerful .Spark Anonymous inner classes are widely used in the source code of ;
  • Anonymous inner class , To define a subclass without a name , And create its objects directly , Then assign a reference to the object to a variable , That is, the instantiated object of the anonymous inner class . Then pass the object to another function to use .
package com.zy.scala.extends_demo
class Person8(val name: String) {
def sayHello = "Hello ,I'm " + name
} class GreetDemo {
// Accept Person8 Parameters , Also stipulates Person8 Class contains only one return String Of sayHello Method
def greeting(p: Person8 {
def sayHello: String}) = {
println(p.sayHello)
}
} object GreetDemo {
def main(args: Array[String]) {
// establish Person8 Anonymous subclass object of
val p = new Person8("tom")
val g = new GreetDemo
g.greeting(p)
}
}

Scala In the abstract class

  • If in the parent class , There are some methods that can't be implemented immediately , You need to rely on different subclasses to override , Rewriting implements different methods . here , You can write these methods in the parent class to contain only method signatures , Form without method body , This form is called abstract method ;
  • In a class , If it contains an abstract method or abstract field, Must use abstract Declare a class as an abstract class , This class cannot be instantiated ;
  • When overriding abstract methods of abstract classes in subclasses , Can not add override keyword ;
package com.zy.scala.extends_demo
abstract class Person9(val name: String) {
// You must indicate the return type , Otherwise, the default value is Unit
def sayHello: String def sayBye: String
} class Student9(name: String) extends Person9(name) {
// You must indicate the return type , Otherwise, the default is
def sayHello: String = "Hello," + name def sayBye: String = "Bye," + name
} object Student9 {
def main(args: Array[String]) {
val s = new Student9("tom")
println(s.sayHello)
println(s.sayBye)
}
}

Scala Middle abstract field

package com.zy.scala.extends_demo
abstract class Person10 (val name:String){
// abstract fields
val age:Int
}
class Student10(name: String) extends Person10(name) {
val age: Int = 50
}

Scala Basics : Object oriented objects and inheritance

  1. Java Basics - The inheritance of the second feature of object oriented (Inheritance)

    Java Basics - The inheritance of the second feature of object oriented (Inheritance) author : Yin Zhengjie Copyright notice : Original works , Declined reprint ! Otherwise, the legal liability will be investigated . One . An overview of inheritance in real life , Inheritance generally means that children inherit the property of their parents . In procedure ...

  2. Java Basics -- object-oriented programming 3( Inherit )

    1. The role of inheritance To extract the common code in the two classes , You can use inheritance to extract repetitive code into a common class . This common class is called a parent class (super class), A class inherited from its parent is called a subclass (sub class). 2.java Following ...

  3. Scala Way of learning ( 6、 ... and )Scala Class 、 object 、 Inherit 、 Trait

    One . class 1. The definition of a class scala Not in the language static Members exist , however scala Allow to use in some way static This is the accompanying mechanism , The so-called accompanying , It's on the linguistic level , hold static Members and non members static For members ...

  4. python Foundation and object , Inheritance and derivation

    Classes and objects The essence of an object is just a namespace , Used to store your own unique properties , The class stores the common properties of the object . __init__ Will trigger automatically when the class is called Two things happen when calling a class : 1. Create an empty object stu1 2. Automatic triggering ...

  5. understand JavaScript Object oriented fundamentals &amp; Prototypes and objects

    Objects in object-oriented languages Always hear something based on objects , object-oriented .  What is an object , If you have an object-oriented foundation, you can ignore it , Let's take a simple example to talk about object-oriented , Object definition , This is more general , But for the JS Come on ...

  6. javascript Object oriented programming of ( Objects and inheritance )

    The conclusion is a little longer , Be careful . Preheat knowledge points Reference type : Value of reference type ( object ) Is an instance of a reference type . stay ECMAScript in , Reference type is a data structure , Used to organize data and functions together . It's called a class in other object-oriented languages , although ...

  7. Scala Learn lesson note 2: functional programming 、Object object 、 Companion 、 Inherit 、Trait、

    1:Scala Learning notes of functional programming : :Scala Functional programming learning : 1.1:Scala Define a simple class , contain field And how , Create object of class , And call its methods : class User { private ...

  8. Section 27 :Java Basic object oriented - static state , The singleton pattern , Inherit the details of knowledge

    Preface Java Basic object oriented - static state , The singleton pattern , Inherit the details of knowledge . static state -static keyword ,static Variable , Static code block , Code block ( No static ), Object creation process , The singleton pattern , Inherit . static state -static keyword // ...

  9. JavaScript object-oriented programming ( 3、 ... and ): Inheritance of non constructor objects

    JavaScript object-oriented programming ( 3、 ... and ): Inheritance of non constructor objects One . What is? " Non constructor " Inheritance ? such as , Now there's an object , be called " Chinese ". var Chinese ...

Random recommendation

  1. solr Import mysql database

    thank ITeye Bloggers viskyzz Shared experiences , The author's basic reference ta Methods . However , When solving the problems in the middle, I also integrate my own experience . see ta Please stamp : http://tbwuming.iteye.com/blog ...

  2. android Add a button to the title bar

    public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowF ...

  3. shell Redirection in (2&gt;&amp;1)

    shell The output can be divided into standard output and error output ,2>&1 in ,2 Stands for error output ,1 For standard output ,& The symbol means that it is followed by a code rather than a file . test.sh echo ' I'm standard output ' ls / ...

  4. Python in collections modular

    Catalog Python in collections modular Counter defaultdict OrderedDict namedtuple deque ChainMap Python in collections ...

  5. utilize MAT Get along well with JVM Memory analysis ( One )

    This article was first published on the official account :javaadu Even though JVM Provides a mechanism for automatic memory management , Trying to lower the development threshold for programmers , It's true that this goal has been achieved , In daily development , We generally don't need to care about the memory release of objects .JVM Most of them use trace count ...

  6. Java Development Notes ( Thirty-one ) Representation of character types

    Previously introduced Java Programming , Or it's a number related calculation , Or reasoning related to logic , At best, only calculators and state machines can be implemented . If you want to Java Applied to a broader business , We have to make it support more flesh and blood business scenarios , And the premise of fullness is to be able to express big ...

  7. Linux File basic operation management

    This is a summary Linux The creation of files and directories in the system , Copy , Move and rename , Including deleting the most common operations . establish 1, Create directory Use command :mkdir practice : Create a directory under the root directory and name it mcgrady 2, create a file send ...

  8. The concurrent snapshot for publication 'xxx' is not available because it has not been fully generated or the Log Reader Agent is not running to activate it

    Replication was deployed on two test servers ( Publish subscribe ) after , It is found that the subscribed table has not been synchronized . Regenerate snapshot , Also reinitialized the subscription , Can't synchronize data , Check in the back Distributor To Subscriber H ...

  9. redis Basic operation

    ''' pip install redis redis It can be seen as a big dictionary in memory redis Five data types --> It refers to the first layer of value The type of value - character string "k1" - Column ...

  10. Android adt-bundle Build the development environment _windows

    A complete copy of this article is :  https://www.jb51.net/article/87953.htm  This article is only used to save learning information . Android There are three ways to develop an environment , Namely JDK+SDK+Ecli ...