Scala中的Getter和Setters

Getter and Setters in Scala are methods that are used to access and instantiate a variable of a class or trait in Scala. These methods have similar functioning as in Java.

Scala中的Getter和Setter是用于访问和实例化Scala中类或特征变量的方法。 这些方法具有与Java中相似的功能。

Let's see the function of each of them in detail,

让我们详细了解它们的功能,

吸气剂 (Getters)

Getters are methods that are used to access the value of a variable of a class/trait.

吸气剂是用于访问类/性状的一个变量的值的方法。

Getting the values of variables is easy and can be done just by calling the name of the variable with the object name.

获取变量的值很容易,并且可以通过使用对象名称调用变量的名称来完成。

    object_name.varaible_name 

Variables always have some restrictions on the usage which is done by access specifiers, so we need to call the variables using general public method calls.

变量总是对使用说明有一些限制,这由访问说明符完成,因此我们需要使用常规的公共方法调用来调用变量。

    object_name.method()

Example:

例:

class Bike 
{ 
	var Model: String= "Harley Davidson Iron 833"
	var TopSpeed: Int= 183
	private var Average= 15

	def getAverage(): Int ={ 
		return Average 
	} 
} 

object MyObject 
{ 
	def main(args: Array[String]) 
	{ 
		var myBike = new Bike() 
		println("Bike Name: " + myBike.Model) 
		println("Top Speed: " + myBike.TopSpeed) 
		println("Average: " + myBike.getAverage) 
	} 
} 

Output

输出量

Bike Name: Harley Davidson Iron 833
Top Speed: 183
Average: 15

二传手 (Setters)

Setters are methods that are used to set the value of a variable of a class/trait.

设置器是用于设置类/特征变量值的方法。

Setting the values of variables is easy and can be done just by calling the name of the variable with the object name.

设置变量的值很容易,可以通过使用对象名称调用变量的名称来完成。

    object_name.varaible_name = value

Variable always have some restrictions on the usage which is done by access specifiers, so we need to call the variables using general public method calls.

变量总是对访问说明有一定的使用限制,因此我们需要使用通用的公共方法调用来调用变量。

    object_name.setterMethod()

Example:

例:

class Bike 
{ 
	var Model: String= ""
	var TopSpeed: Int= 0
	private var Average= 0
	
	def setAverage(x : Int){
		Average = x;
	}
	def getAverage(): Int ={ 
		return Average 
	} 
} 

object MyObject 
{ 
	def main(args: Array[String]) 
	{ 
		var myBike = new Bike() 
		myBike.Model = "BMW S1000 RR"
		myBike.TopSpeed = 300
		myBike.setAverage(15) 
		
		println("Bike Name: " + myBike.Model) 
		println("Top Speed: " + myBike.TopSpeed) 
		println("Average: " + myBike.getAverage) 
	} 
} 

Output

输出量

Bike Name: BMW S1000 RR
Top Speed: 300
Average: 15


翻译自: https://www.includehelp.com/scala/getters-and-setters.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值