Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Scala2.11.7 Learning Notes (6) categories and objects

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Lu Chunli's work notes are not as good as bad notes.

1. Extended class

Extends is a reserved word that implements inheritance in Scala

Class week extends month {.}

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

Week class is a subclass of month class, and month class is a superclass of week class.

Subclasses can override members of a superclass (fields, methods)

Class week (val num: Int) extends month (val num: Int) {.}

Singleton objects can also inherit from a class, with the same inheritance syntax as the class: object day extends week {.}

Rewrite

Using override reserved words to rewrite methods and fields in Scala

Class week extends month {override def firstday () {.}}

The field or method after the override reserved word declaration is an override of the superclass or can be written in the class definition parameters.

Class week (overrideval lastday: String) extends month (val lastday: String)

Redefined fields and methods cannot be rewritten (override), and different methods (parameter type or number) cannot be rewritten.

Scala > class month {| def secondary (m: String) {| println ("secondary is" + m); |} |} defined class month scala > scala > class week extends month {| override def secondary (m: String) {/ / rewrite this method | println ("secondary is" + m); |} |} defined class week

2. Rewrite rules

Rewrite def

Using val: using val to rewrite methods with no parameters for superclasses

Use the def: subclass method to duplicate the name of the superclass member

With var: both getter and setter methods are overridden, and only the getter method is overridden.

Rewrite val:

With a private field of the val: subclass renamed with the field of the superclass, the getter method overrides the getter method of the superclass

Rewrite var:

Use var: only when the var of the superclass is abstract can it be overridden, otherwise the var of the superclass will be inherited.

/ / create a new file month.scala, which contains: abstract class month {val zero: Int; val one = 25; / / you can rewrite var two = 15 with val in a subclass; / / you cannot rewrite it with var in a subclass because it is not an abstract var three: Int; def firstday; / / you can rewrite def now with val in a subclass / / def now_ can be rewritten with var in subclasses Def lastday (m: Char) = {} / / can be rewritten in a subclass with def} / / compile the file D:\ LuclAppServ\ scala-SDK\ source > scalac month.scalaD:\ LuclAppServ\ scala-SDK\ source > javap.exe-private month.class// through the javap command to view the generated file Compiled from "month.scala" public abstract class month {/ / val variable and private final int one is initialized / / var variable and private int two; / / val variable is initialized but abstract, directly generates getter method public abstract int zero (); / only getter method public int one (); / / has both getter and setter methods (= escaped as $eq) public int two (); public void two_$eq (int); / / var variable can be abstract, directly generates getter and setter method public abstract int three () Public abstract void three_$eq (int); / / other abstract methods public abstract void firstday (); public abstract void now (); public abstract void now_ (); / / with method body, non-abstract method public void lastday (char); / / constructor public month ();}

The week.scala code generated by the IDE tool is as follows

/ * @ author lucl * / class week extends month {overrideval zero: Int = 10; override var three: Int = 3; override def firstday: Unit = {println ("method of firstday.");} override def now: Unit = {println ("method of now.");} override def now_: Unit = {println ("method of now_.");}} object week {def main (args: Array [String]) {var w = new week () Println (w.zero + "\ t" + w.now);}}

View the generated codes of the slave subclass

D:\ LuclAppServ\ workspaces\ scala\ scalaproj\ bin > javap-private week.classCompiled from "week.scala" public class week extends month {private final int zero; private int three; public int zero (); public int three (); public void three_$eq (int); public void firstday (); public void now (); public void now_ (); public week (); public static void main (java.lang.String []) } D:\ LuclAppServ\ workspaces\ scala\ scalaproj\ bin > javap-private week$.classCompiled from "week.scala" public final class week$ {public static final week$ MODULE$; public static {}; public void main (java.lang.String []); private week$ ();}

Description:

The subclass constructor runs after the superclass constructor, and the return value may be incorrect after the subclass called by the superclass constructor is overridden.

/ * @ author lucl * / class A {val num = 31; val days = new Array [Int] (num); println ("When invoke Class A the length of days is" + days.length + "."); def dayLength = {println ("Class A: the length of days is" + days.length + ".")}} / * * @ author lucl * / object B extends A {overrideval num = 7; def main (args: Array [String]) {dayLength Println ("The finally value of num is" + num);}}

Running result:

The constructor of An is executed before constructing the B object, and the num is initialized to 31 days and initialized to the Array array.

Num needs to be called when initializing the Array array, but the num is overridden by the subclass, but the constructor of B has not been called yet, and num is initialized to 0 days and initialized to an array of length 0.

When the constructor of An is finished, the constructor of B is executed, and the num is initialized to 7, but at this time the days in A has been initialized and its initialization information will not be updated, and the array length of days is 0.

Solution:

Declare the val of a superclass as final (can no longer be overridden by subclasses)

Declare the val of the superclass as lazy

Use pre-defined syntax in subclasses.

A. Final

When the num in class An is declared as final val num: Int = 7, the field cannot be overridden in the subclass.

B. Lazy

/ * * @ author lucl * / class A {lazy val num = 31; / / tagged via lazy val days = new Array [Int] (num); println ("When invoke Class A the length of days is" + days.length + "."); def dayLength = {println ("Class A: the length of days is" + days.length + ".")}} / * * @ author lucl * / object B extends A {override lazy val num = 7 Def main (args: Array [String]) {dayLength; println ("The finally value of num is" + num);}}

Running result

c. Define in advance

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

Class B extends {overrideval num = 7;} with A {.}

/ * * @ author lucl * / object B extends {overrideval num = 7;} with A {def main (args: Array [String]) {dayLength; println ("The finally value of num is" + num);}}

Execution result:

3. Abstract class

Classes that cannot be instantiated are called abstract classes, marked with the reserved word abstract

One or more members of an abstract class are not fully defined. These members that are not fully defined are abstract fields or methods.

/ * * @ author lucl * / abstract class year {val name: Array [String]; / / Abstract val with an abstract getter method var num: Int; / / Abstract var, with abstract getter/setter method def sign; / / No method body / function body, is an abstract method}

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

You do not need to use override reserved words to override abstract methods and abstract fields.

Protection

When a class does not want to be integrated or extended, add the final reserved word before the class declaration

Final class year {.}

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

Class year {final def sign {.}}

When some members of a superclass need to be inherited by a subclass and do not want to be visible to members other than the subclass, add the protected reserved word before the member declaration

Protected [this], which limits access to the current object (subclasses are also inaccessible), similar to private [this]

/ * * @ author lucl * as long as one member of the class is abstract, the class needs to be declared abstract * / abstract class Human {var name: String; / / abstract field def sleep (): String; / / abstract method def info (address: String);} / * / abstract class Teacher (tname: String, age: Int) extends Human {println (tname + "\ t" + age) Override var name: String = tname; / / if you declare the class as def sleep = "8 hours", you will be prompted to return Unit override def sleep (): String = "8 hours."; def info (address: String) where you call super.sleep () below. } / * when Worker inherits Teacher, there are two parameters name and age need to pass parameters from Worker * the parameter name of Worker needs to be the same as that in Teacher, otherwise IDE will prompt error * / class Worker (tname: String, age: Int, salary: Int) extends Teacher (tname, age) {override def info (address: String) {println (tname + "'home is in" + address) Println (tname + "'s age is" + age + ", earn ¥" + salary + ".");} override def toString = {tname + "is a worker, sleep" + super.sleep;}} object AbstractClassOps {def main (args: Array [String]) {val w = new Worker ("zhangsan", 25, 3000); w.info ("BeiJing"); println (w) }} / * zhangsan 25 zhangsan' home is in BeiJing zhangsan's age is 25, earn ¥3000. Zhangsan is a worker, sleep 8 hours.*/

4. The private attribute of the class

/ * * @ author lucl * / / the class Person {/ / age of type public must be assigned by default, otherwise the class must be private var age: Int = 0 of abstract; / / without private modification, the method with no public by default can be omitted (), and can be omitted when called. Def increment () = age + = 1; / / if the declared method does not take (), the () def current = age; / / class can directly access the private property of the accompanying object def speak = Person.sayHello;} class Student {/ * declared as a parameter of type private, and can only be accessed through the function of the current class * / private var privateAge: Int = 0 / / only the current instance object of the class can be accessed. Other incoming objects (such as the following other) will not be accessible to the variable private [this] val name: String = ""; / / Custom getter/setter method, which is used to manipulate the private field def age = privateAge; def age_ (newAge: Int) {privateAge = newAge. } / * the use of this object indicates that the current object calling the method * / def sameStudent (other: Student) = {/ / the equal sign above indicates that a result is returned, otherwise the final true will prompt: / / a pure expression does nothing in statement position; / / you may be omitting necessary parentheses if (this.privateAge! = other.privateAge) {false } / * the name object will not be accessible via other * value name is not a member of Student * / / * if (this.name! = other.name) {false;} * / true;} / / in student, the sayHello method cannot be accessed directly through the Person class. Prompt: / / method sayHello in object Person cannot be accessed in object Person / / def speak = Person.sayHello / / but it can be accessed in the following ways: var p = new Person; p. String; / / the object} / * is directly executed here as the accompanying object of the class, and the class is the accompanying class of the object * / object Person {def main (args: Array [String]) {var p = new Person (); println ("age is:" + p.age); / / the private attribute p.increment can be accessed Println ("age is:" + p.age); println ("current is:" + p.current); / / with () prompts "Int does not take parameters" / / p.current (); val s = new Student (); / / variable privateAge in class Student cannot be accessed in Student / / s.privateAge; println (s.age); s.age20; println (s.age) } private def sayHello () {println ("Singleton object Person to say.");}} / * / / output result age is: 0 age is: 1 current is: 1 Singleton object Person to say. 0 20 minutes /

5. Nested classes

Scala allows any syntax structure to be nested within any syntax structure, so you can define classes in classes, similar to inner classes in Java.

Members of the external class can be accessed in the inner class, which is implemented using the external class .this or pointer.

Scala > class HelloWorld {pointto = > val value2 = "HelloWorld"; class HI {var value3 = HelloWorld.this.value2; var value4 = pointto.value2;} scala > var one = new HelloWorld;one: HelloWorld = HelloWorld@4b134f33scala > one.value2;res52: String = HelloWorldscala > class Family (val hname: String, val wname: String) {class Husband (var name: String) {println ("Husband is:" + name) } class Wife (var name: String) {println ("Wife is" + name);} def info () {var husband = new Husband (hname); var wife = new Wife (wname); println ("This family holds husband" + husband.name + ", wife" + wife.name);} scala > val f = new Family ("Tom", "Jerry"); f: Family = Family@62de96e8scala > f.info () Husband is: TomWife is JerryThis family holds husband Tom, wife Jerry

Java inner class: inner class belongs to outer class

/ * @ author lucl * Java inner class example * shows that the Java inner class is * / public class JavaOuter {private String name; public JavaOuter (String name) {this.name = name;} / * * inner class * / / once the inner class is decorated with static, it becomes a static inner class. Class Inner {private String name; public Inner (String name) {this.name = name;} public void foo (Inner inner) {System.out.println ("\ t" + JavaOuter.this.name + "\ t" + inner.name);}} public void foo () {System.out.println ("Outer:" + this.name) } / * @ param args * / public static void main (String [] args) {JavaOuter outer1 = new JavaOuter ("Spark"); JavaOuter outer2 = new JavaOuter ("Hadoop"); JavaOuter.Inner inner1 = outer1.new Inner ("scala"); JavaOuter.Inner inner2 = outer2.new Inner ("java"); outer1.foo (); inner1.foo (inner1) Outer2.foo (); inner2.foo (inner2); outer1.foo (); inner1.foo (inner2); / / here inner1 can call inner2}} / * * / / output result Outer: Spark Spark scala Outer: Hadoop Hadoop java Outer: Spark Spark java*/

Scala inner class: the inner class belongs to the object of the outer class

/ * * @ author lucl * Scala inner class example * shows that the Scala inner class is * / class ScalaOuter (val name: String) {outer = > / * inner class * / class Inner (val name: String) {def foo (inner: Inner) {println ("\ t" + outer.name + "\ t" + inner.name + ".") } def foo () {println ("Outer:" + outer.name);}} object OOPInScala {/ * main method * / def main (args: Array [String]) {val outer1 = new ScalaOuter ("Spark"); val outer2 = new ScalaOuter ("Hadoop"); val inner1 = new outer1.Inner ("scala"); val inner2 = new outer2.Inner ("java"); outer1.foo Inner1.foo (inner1); outer2.foo; inner2.foo (inner2); / / for scala, the inner1 cannot pass inner2 as a parameter when calling the foo method. / / IDE prompt: type mismatch; found: outer2.Inner required: outer1.Inner / / inner1.foo (inner2);}} / * / / output result Outer: Spark Spark scala. Outer: Hadoop Hadoop java.*/

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report