Scala Foundation 06: Inheritance

Source: Internet
Author: User
Tags traits

Scala inheritance inheritance is an extension of a class

Extends is a reserved word that implements inheritance in Scala:

Class Week extends month{...}

Description

The week class inherits all non-private members of the month class.

The week class is a subclass of the month class, and the month class is a superclass of the week class.

Subclasses can override members of a superclass (with the same name and parameters).

Like Java, a class is no longer inherited if it is declared final. If the method or field is declared final, the method can no longer be overridden.

Note: Final in Scala is a little different from final in Java, and final fields in Java are immutable. Not in Scala.

Object Inherits Class

Cases:

Class Student (Name:string, Age:int, Val major:string) extends person (name, age) {  println ("This is subclass of Per Son, Major is: "+ Major)}

A singleton object can also inherit from a class, the same as the inheritance syntax of a class:

Object Day extends week{...}

Rewrite

Use override reserved word for method, field rewrite in Scala

Class Week extends month{  override def FirstDay = {...}}

Override can also be used for the main constructor parameters of a class:

Class Week (override Val lastday:string) extends month{...}

A subclass that overrides or modifies Scala examines its superclass, but the superclass's modifications do not check its subclasses.

Cases:

Class Student (Name:string, Age:int, Val major:string) extends person (name, age) {  println ("This is subclass of Per Son, Major is: "+ Major)  override def tosting =" Override Tosting "}

Overrides include fields and methods, but methods with different parameters can not be overridden

Class month{def secondday (m:string) ={...}} Class Week extends month{def secondday ={...}

Rules:

Rewrite def

With Val: use Val to rewrite superclass with no parameter method (getter)

Use Def: Subclass method and Superclass method duplicate name

Use Var: simultaneously rewrite getter, setter method, only rewrite Getter method error

Rewrite Val

With Val: A private field of a subclass that has the same name as a superclass field, the Getter method overrides the superclass's Getter method

Rewrite var

var: And when the superclass's Var is abstract to be rewritten, the Var of the superclass will be inherited.

Cases:

Class month{

Val one = 25//Can be overridden in subclasses with Val

var = 15//cannot be overridden with Var in subclasses because it is not abstract

var three:int

def firstday =//Can be overridden in subclasses with Val

def now =//can be overridden in subclasses with Var

def now_ =

def lastday (M:char) ={}//Can be overridden in subclasses with Def

}

Summarize:

Subclasses, Def can only override the superclass of the def,val can rewrite the superclass of Val or Def,var without parameters can only override the superclass in the abstract var or superclass Getter/setter pair.

Type checking and conversion

Use the Isinstanceof method to test whether the class of an object inherits from a class. Use the Asinstanceof method to convert a reference to a child class reference.

if (P.isinstanceof[employee]) {  val s = p.asinstanceof[employee]  //S is of type Employee  //...}

If P points to an object of the employee class and its subclasses (such as the manager Class). Then P.isinstanceof[employee] returns TRUE.

If p is null, then P.isinstanceof[employee] will return false, then P.asinstanceof[employee] will return null.

If P is not an Employee, then P.asinstanceof[employee] throws an exception.

If you want to judge that "P is pointing to an employee object, not the object of its child class." "You can use:

if (P.getclass = = Classof[employee])

The Classof method is defined in the Scala.predef object and is therefore automatically introduced.

Description: For type checking and conversion, Scala is more inclined to use pattern matching.

Type checking and conversion for Scala and Java
Scala Java
OBJ.ININSTANCEOF[C1] obj instanceof C1
OBJ.ASINSTANCEOF[C1] (C1) obj
CLASSOF[C1] C1.class

Anonymous sub-class

Val alien = new Person ("Fred") {  def greeting = "Greetings, earthling! My name is Fred "}

Abstract class

Classes that cannot be instantiated are called abstract classes.

One or several members of an abstract class are not fully defined, and those members that are not fully defined are called abstract methods or abstract fields.

The abstract class is marked with an abstract reserved word.

Abstract year{

Val Name:array[string]//abstract Val, with an abstract getter method

var num:int//abstract var with abstract Getter/setter method

def SIGN1//No method body, is an abstract method.

def sign2:int//No function body, is an abstract function.

}

As long as there is any abstract member in the class, you must use the abstract tag.

Overriding an abstract method, an abstract field does not require an override reserved word.

Abstract field, which is a field without an initial value.

Abstract method, that is, a method without a method body.

Protection

When a class does not want to be inherited or expanded, it can be preceded by a final reserved word in the class declaration.

Final Class year{...}

When some members of a class do not want to be overridden, you can add the final reserved word before the member declaration.

Class year{

Final def sign{...}

}

When some members of a superclass require a quilt class to inherit and do not want to be visible to members outside of the subclass, precede the member declaration with a protected reserved word.

Protected[this], set access rights to the current object, similar to Private[this].

A protected member of a class is visible to its subclasses, not to its superclass:

Class year{

Protected Def sign{...}

}

Discrimination: The difference between private and private[this].

Inheritance and constructors

The sub-class constructor runs after the superclass constructor is run.

The returned value may be incorrect after a member of the quilt class is called in the constructor of the superclass:

Class month{

Val num = 31

Val days = new Array[int] (num)

}

Class Week extends month{

Override Val num = 7

}

Val A=new Week

The constructor for month is executed before the week object is constructed, num is initialized to 31,month to initialize the days array, and NUM is called, but the Num Quilt class week is overridden, but because the week constructor has not yet been called,

The value of NUM is not initialized at this time, so the return 0,days is set to an array of length 0, and the month constructor runs

Complete, execute the week constructor, Num is initialized to 7

Workaround:

Declares the Val of the superclass as final

Declare the Val of the superclass as lazy

Using the advance definition syntax in subclasses

Defined in advance

Initializes a field for the subclass before the constructor of the superclass is run.

Place the block of statements that need to be defined in advance between the extends and the superclass, followed by the with reserved word.

Class Week extends {override Val num =7} with month{...}

Define in advance the right side of "=" If you need to invoke the B member in the class, unless the B member has been defined in advance before the call:

Class Week extends{

Override Val Num=7

Override Val num2=num+1//Allow NUM to be defined in advance

Override Val num4=num2+num3//not allowed, num3 not defined in advance

}with month{...}

Characteristics

A new feature in JAVA8: The default method, which can be implemented in interface.

Scala features a interface similar to Java 8.

Scala classes can only inherit from a parent class, but can be expanded by multiple traits.

Scala does not support multiple inheritance, instead it is a trait.

Trait can be mixed into related classes as tool methods.

Problems with multiple inheritance

A subclass can have only one superclass, and a superclass may have more than one subclass.

That is: Class Week extends month,year is not legal.

Why?

If a subclass inherits from a different superclass, a subclass of the same name in a different superclass does not know how to handle it.

Multiple inheritance produces a diamond inheritance problem.

Solving problems that can result from multiple inheritance consumes more resources than multiple inheritance yields

Scala uses traits to achieve the same effect as multiple inheritance.

A class can be extended from one or more traits, and a trait can be extended by multiple classes.

Traits can limit what classes are extended.

All Java interface can be used as a trait in Scala.

When the interface uses the trait

Trait logger{

def log (msg:string)

}

Realize

There is no implements in Scala, so use extends.

Class Consolelogger extends logger{

def log (msg:string) {println (msg)}

}

The override keyword is not required in the method of overriding the trait.

overriding abstract methods in attributes

Trait logger{

def log (msg:string)

}

Overriding attributes requires the use of override.

Trait Timestamplogger extends logger{

Override def log (msg:string) {

Super.log (New Java.util.Date () + "" +msg)

}

}

The trait is a basic unit of code reuse in Scala, encapsulating the definition of methods and fields.

The definition of the trait uses the reserved word trait, which is similar to the class definition except that it cannot have construction parameters.

Trait reset{

def reset (M:int,n:int) = if (M >= N) 1

}

Once the trait is defined, it can be mixed (mixin) into the class.

Class Week extends Reset {...}

When you want to mix multiple traits, take advantage of the WITH keyword:

Class Week extends reset with B with C {...}

The members of a trait can be abstract, and there is no need to use an abstract declaration.

Similarly, the abstract method of overriding the trait does not require an override.

However, multiple traits that override the same trait in an abstract way need to be overridden.

In addition to the inclusion of traits in the class definition, you can also mix traits in a trait definition:

Trait reseting extends reset{...}

To mix attributes when constructing an object:

Val five = new month with reseting

The structure of the trait is sequential: From left to right is constructed.

Constructors are constructed in the following order:

Super class

Parent Trait

The first trait of

The second trait (the parent trait does not repeat the structure)

Class

If class A extends B1 with B2 with B3 ....

So, string B1, B2, B3 ... And the right side wins.

The application of the trait

One of the main applications of the trait is the interface, which automatically adds methods to the class based on the existing methods of the class.

Using attributes to achieve rich interfaces:

Constructs a trait that has a small number of abstract methods and a large number of concrete methods based on abstract methods.

Then, as soon as the trait is mixed into a class, the class overrides the abstract method, and the classes automatically get a lot of concrete methods.

Trait logger{

def log (msg:string)

def warn (msg:string) {log ("server" +msg)}

def server (msg:string) {log ("server" +msg)}

}

Class Week extends logger{

def log (msg:string) {println (msg)}

Server ("HI")

}

Another application aspect of the trait is that it provides stackable changes to the class (super reserved words)

When you add multiple attributes to a class that are called each other, the process starts at the last one.

A method call such as Super.foo () in a class is statically bound and is explicitly called the Foo () method of its parent class.

When Super.foo () is written in a trait, its invocation is dynamically bound. The implementation of a call is determined when each trait is mixed into a specific class.

As a result, the order in which the traits are mixed is different in their execution.

Abstract class Intqueue {def get (): Int;def put (X:int)}

Class Basicintqueue extends Intqueue {

Private Val buf = new Arraybuffer[int]

def get () = Buf.remove (0)

def put (X:int) {buf + = x}

}

Trait incrementing extends Intqueue {

Abstract override def put (X:int) {

Super.put (x + 1)

}

}

Trait doubling extends Intqueue {

Abstract override def put (X:int) {

Super.put (2 * x)

}

}

Object TestClient extends App {

Val queue1 = (new basicintqueue with incrementing with doubling)

Doubling.put (2*2)->incrementing.put (4+1)

Queue1.put (2)

println (Queue1.get ())//result is 5

Val queue2 = (new basicintqueue with doubling with incrementing)

Incrementing.put (2+1)->doubling.put (2*3)

Queue2.put (2)

println (Queue2.get ())//result is 6

}

App features only support single thread. And the normal main can support multithreading.

Extending classes and traits

Constructs an object that extends a class of the specified class and trait, with all the attributes given in the object definition

Scala file access

Access to files in Scala requires the use of Scala.io.Source objects.

Example: reading a local file.

def main (args:array[string]) {

accessing files

Val file = Source.fromfile ("D:\\scala-test.txt")

for (line <-file.getlines) {

println (line)

}

}

If using:

For (line <-file) {

println (line)

}

Instead of reading the data in a row, it reads and outputs a word.

Example: reading a network file.

def main (args:array[string]) {

Accessing the network URL

Val file = Source.fromurl ("http://www.baidu.com")

for (line <-file.getlines) {

println (line)

}

}

Scala Foundation 06: Inheritance

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.