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

Scala Note arrangement (3): Scala object-oriented-Class detailed explanation 1

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

Share

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

[TOC]

Getter and setter simple classes and no-parameter methods

It should be noted that the official reference materials explain this aspect in great detail, at present, for entry, there is no need to achieve such an understanding, as long as it can be developed. In this part, I give some official documentation instructions, but the following customizations and notes can simply explain that they can be used.

Class PersonOps {private var age = 0 / / you must initialize a field def increment () {age + = 1} / / method defaults to the public def currentAge () = age}

1) in Scala, the class is not declared as public. Scala source files can contain multiple classes, all of which have public visibility.

2) how to make the call?

Object MainOps {def main (args: Array [String]) {val personOps = new PersonOps personOps.increment () println ("currentAge= >" + personOps.currentAge ())}}

3) you cannot call age directly with a class, because age is a private field and can only be accessed in PersonOps.

4) No parameter method

Println ("currentAge= >" + personOps.currentAge ()) println ("currentAge= >" + personOps.currentAge)

Suggestion: use () when setting the value, that is, when changing the state value or state of the object, and removing () from the value (which does not change the state and value of the object) is a good style, which is also the method in our case.

PersonOps.increment () println ("currentAge= >" + personOps.currentAge)

5) you can enforce this style by declaring currentAge without ():

Class PersonOps {private var age = 0 / / you must initialize a field def increment () {age + = 1} / / method defaults to the public def currentAge = age}

Result: in this way, when calling, you must make a method call without ()

Println ("currentAge= >" + personOps.currentAge)

6) attributes with getter and setter

Attribute definition in Java

Public class PersonAge {/ / this is Java private int age; public int getAge () {return age;} public void setAge (int age) {this.age=age;}}

How is getter and setter better than common fields (public)?

Getter and setter methods are better than public fields because they allow you to start with a simple get/set mechanism and make improvements when needed.

5) getter and setter methods in scala

Class PersonA {var age = 0}

A.Scala generates JVM-oriented classes with a private age field and corresponding getter and setter methods. These two methods are public because we did not declare age as private. For private fields, the getter and setter methods are also private.

a. In Scala, getter and setter are called age and age_= respectively, for example:

Val personA = new PersonAprintln ("startAge= >" + personA.age) personA.age = 21println ("endAge= >" + personA.age)

Execute the following command:

Scalac PersonOps.scala\ src\ main\ scala\ tw\ tw > javap-p PersonA.classCompiled from "PersonOps.scala"

Then the following is generated:

Public class tw.PersonA {private int age; public int age (); public void age_$eq (int); public tw.PersonA ();}

As you can see, the compiler created age and age_$eq because JVM does not allow = in the method name

Note: in Scala, the getter and setter methods are not named getXxx and setXxx, but they have the same intention. Later on, I'll show you how to generate Java-style getXxx and setXxx methods to make your Scala classes interoperable with Java tools.

Customized getter/setter method

Instead of making this part too complicated, you can use the Java version of the getter/setter method, such as the following class:

Class Student {private var age:Int = 0 def setAge (age:Int): Unit = {this.age = age} def getAge () = age}

The tests are as follows:

Scala > val s = new Student () s: Student = Student@1608bb5dscala > sres200: Student = Student@1608bb5dscala > s.getAge () res201: Int = 0scala > s.getAgeres202: Int = 0scala > s.setAge (18) scala > s.getAgeres204: Int = 18

There is a lot of official knowledge about getter/setter, so when you get started, you can ignore these cases and be able to develop with scala from the point of view of Java.

@ BeanProperty comment

If you use the @ BeanProperty annotation on the attribute, the getter/setter method is automatically generated, but it is important to note that it does not hide the original property, which means that the original property is directly accessible and cannot be decorated with private.

Look at the following example:

Import scala.beans.BeanPropertyclass Student {@ BeanProperty var age:Int = 0}

The tests are as follows:

Scala > var s = new Students: Student = Student@46482990scala > s.getAge () res205: Int = 0scala > s.setAge (18) scala > s.getAge () res207: Int = 18scala > s.ageres208: Int = 18 Summary

There is a lot of wordiness above, but in fact, it is OK to explain it directly with the following code:

/ * * scala object-oriented Chapter 1 * on object Construction * Class Construction (like java) * * to run a scala program, it cannot be executed in class, but needs to be executed in object * you can treat all fields and members in this object as static members in java * * when creating a scala function, if the function is empty. We can omit this () when we create it, but we can't use the method with () when we visit it * on the contrary, we can use it. You can also call * ab.foreach (println) * * without (). Why do we create corresponding getter and setter in javabean pair fields * attributes with getter and setter * for the security of the program? * block some illegal operations Improve the robustness of the program * / object _ 01ClazzFieldsOps {def main (args: Array [String]): Unit = {val person:Person = new Person () person.increment () println (person.currentAge ()) println (person.currentAge) val stu = new Student// stu.age =-1 stu.setAge (- 4) stu.getNameval e = new Employee} } class Person {private var age:Int = 0 / / create a privatized member of type Int def increment (): Unit = {age + = 1} def currentAge () = age} class Student {private var age:Int = 15 private var name:String = "Liu Qian" def setAge (a:Int): Unit = {if (a)

< 1) { throw new RuntimeException(s"你们家的孩子才是($a)岁呢") } age = a } def getAge = age def getName = name}class Employee { @BeanProperty var age:Int = 5}构造器 关于构造器的说明和使用,直接看下面的测试代码就可以了,非常简洁: package cn.xpleaf.bigdata.p2.constructor/** * scala中的类的构造器说明 * scala类的构造器分为主构造器和辅助构造器 * 其构造方式不同于java中的构造方式,public 类名(参数列表){},在scala中的构造器如何定义? * scala中把类名后面的一对{}括起来的内容称为主构造器的函数体,默认的主构造器为空参构造器, * 如何定义一个有参的主构造器呢? * 就在类名后面写上函数的定义即可 * * 当主构造器满足不了我们的需求之后,我们就可以创建更多的辅助构造器来配合我们的业务,辅助构造器如何创建? * def this // 辅助构造器的函数名是this * 注意,在辅助构造中的第一句话,必须是调用该类的主构造器或者其他辅助构造器,this(参数) * * 在一个类中只能有一个主构造器,可以有若干辅助构造器,在辅助构造器的第一句话,调用this * */object _02ConstructorOps { def main(args: Array[String]): Unit = { val p = new Person // p.show() println("=================================") val stu = new Student("前向刘", 17) stu.show() println("=================================") val s = new Student println("=================================") val s1 = new Student(true) }}class Person { private var name:String = "刘向前" private var age:Int = 18/* def Person(n:String, a:Int): Unit = { name = n age = a println("这是scala中的构造器吗?") } def Person(): Unit = { println("这是scala中的构造器吗?") }*/ println("这是scala中的构造器吗?") def show() = println(s"name is $name and age is $age")}class Student(var name:String, var age:Int) { def this() { this("刘银鹏", 25) println("this is 辅助构造器") } private var married:Boolean = false def this(isMarried:Boolean) { this() married = isMarried println(s"this($isMarried) 是另外一个构造器") } println("这是scala中的构造器吗?") def show() = println(s"name is $name and age is $age") // show() // 类构造时就会执行该方法,属性name和age也是默认有的,因为在主构造器中有}内部类 直接看下面的一个完整案例: package cn.xpleaf.bigdata.p2.inner/** * 事物的内部还包含着事物,被包含的事物不能使用非常简单的成员变量来描述,只能使用更为复杂的结构去描述, * 这个时候就用我们的内部类去定义 * * 当多个变量重名的时候,遵循一个原则:局部优先 public class InnerClassOps { public static void main(String[] args) { Outer.Inner i = new Outer().new Inner(); i.show(); } } class Outer { private int x = 5; class Inner { private int x = 6; public void show() { int x = 7; System.out.println("Inner show: " + x); } } } this关键字,是本类的引用,当前类的实例的引用 外部类的引用使用外部类名.this scala同样提供了一种较为简洁的写法,就是在我们的最外层大括号里写一个引用名称outer =>

When you need to call a member of an external class in an inner class, use outer. Exe directly. Member replaces the external class name .this * / object _ 03InnerClassOps {def main (args: Array [String]): Unit = {val outer = new Outer val inner = new outer.Inner inner.show ()}} class Outer {o = > privateval x = 5 class Inner {I = > private var x = 6 def show (): Unit = {val x = 7 println ("Inner show:" + this.x) / / 6 println ("Inner show: "+ i.x) / / 6 println (" Inner show: "+ Outer.this.x) / / 5 println (" Inner show: "+ o.x) / / 5}

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