Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

The inheritance of big data's tutorial Scala series

Shulou Source: shulou.com Published: 2022-06-03 07:31:45 11月23日 Update

1. Extended class

Classes are extended in Scala in the same way as Java by using the extends keyword

You can declare a class as final so that it cannot be expanded

You can also declare a single method or field as final to ensure that it cannot be overridden. Note that unlike Java, final-decorated fields in Java mean immutable.

5.3.2. Rewriting method

Overriding a non-abstract method in Scala must use the override modifier

Call the method of the superclass in the subclass, using super, which is the same as Java.

Fields and methods modified by 5.3.3.protected

Fields or methods modified by protected can be accessed by their subclasses

Unlike Java, protected-decorated members are not visible to the package to which the class belongs

Protected [this], access is limited to current objects

You can use package modifiers to change the visibility of protected-decorated members

5.3.3. Type checking and conversion

Scala

Java

Test whether an object belongs to a given class

Obj.isInstanceOf [C]

Obj instanceof C

Forced type conversion

Obj.asInstanceOf [C]

(C) obj

Get the class information of an object

ClassOf [C]

C.class

5.3.4. Construction of superclass

The following code defines a subclass and a main constructor that invokes the superclass constructor

Class Employ (name: String, age: Int, val Salary:Double) extends Person (name,age)

The following code shows the inheritance of the class, the implementation of the interface, etc.

Object ClassDemo {

Def main (args: Array [String]) {

Val h = new Human

Println (h.byScala ())

}

}

/ / equivalent to Java

Trait Coding {

Def byJava (flag: Boolean): Unit = {

If (flag)

{

Println ("I can code by Java")

}

Else {

Println ("I can't code by Java")

}

}

/ / methods that are not implemented default to abstract methods

Def byScala (): String

}

/ / Abstract class

Abstract class Animal {

Def run (): Int

Val name: String

}

Class Human extends Animal with Coding {

Val name = "abc"

/ / how many times do I print "ABC"?

Val T1 and T2, (a, b, c) = {

Println ("ABC")

(1, 2, 2, 3)

}

Println (a)

Println (t1.room1)

/ / rewriting a non-abstract method in Scala must be decorated with override

Override def byJava (flag: Boolean): Unit = {

Println ("Coding by Java and Scala")

}

Def byScala (): String= {

"coding by Scala"

}

/ / when overriding the abstract method of a superclass in a subclass, you don't need to use the override keyword.

Def run (): Int = {

one

}

}

Tags: Methods fields subclasses objects differences codes keys keywords members interfaces types constructors consistent single meaning ownership methods permissions class information faceted Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei NVidia vpn Redmi Docker