scala 类中的对象是类_Scala类和对象– Singleton对象,伴侣类

scala 类中的对象是类

Earlier we learned about Scala Programming Language and it’s installation on Windows and *nix systems. Scala is an object oriented functional programming language, so today we will look into Scala Classes and Objects in brief.

之前,我们了解了Scala编程语言及其在Windows和* nix系统上安装 。 Scala是一种面向对象的功能编程语言,因此今天我们将简要介绍一下Scala类和对象

Scala类和对象 (Scala Class and Object)

Classes can be defined as a static template from which many objects can be instantiated at runtime.

可以将类定义为静态模板,可以在运行时从中实例化许多对象。

Let us look into an example of how to define a class in Scala;

让我们看一下如何在Scala中定义类的示例;

class Student() {
 	var total:Int = 0
 	def calculateTotal(ma1:Int,ma2:Int) {
 	total = ma1 + ma2
 	}
 	override def toString(): String = "(" + total + ")";
}

Here we are defining a class named Student using the keyword “class”. We are then declaring a variable total and initializing the variable value to zero. A method calculateTotal is defined with arguments ma1 and ma2 which are the individual marks/scores of two subject. The scores are added and a grand total is calculated and stored in the “total” variable.

在这里,我们使用关键字“ class”定义一个名为Student的类。 然后,我们声明一个变量total并将变量值初始化为零。 一种方法calculateTotal与参数MA1和MA2这是两个受治疗者的个体标记/分数定义。 分数相加,计算出总计,并将其存储在“总计”变量中。

We are overriding the toString standard method so that when we print it, we get useful information. Below image shows how it will look in the Scala terminal.

我们将重写toString标准方法,以便在打印它时,我们可以获得有用的信息。 下图显示了它在Scala终端中的外观。

Now we shall test the method by creating an object of the Student class as shown below.

现在,我们将通过创建Student类的对象来测试该方法,如下所示。

object Stud1 {
	def main(args:Array[String]) {
	val totalMarks = new Student()
	totalMarks.calculateTotal(55,60)
	println("Grand Total Marks of the Student is"+totalMarks)
}
}

Stud1 is an object of the Student class. We define the main method with String type array as an argument. We create totalMarks as an instance of Student class using the new keyword and invoke the calculateTotal method passing the marks and print the total marks secured.

Stud1是Student类的对象。 我们使用String类型数组作为参数定义main方法。 我们使用new关键字将totalMarks创建为Student类的实例,并调用传递标记的calculateTotal方法并打印受保护的总标记。

Please note that the main method should be defined since it is the entry point for the program execution.

请注意,应定义main方法,因为它是程序执行的入口点。

Now run the above code by invoking the main method of Stud1 as

现在通过调用Stud1的主要方法来运行上面的代码:

scala>Stud1.main(null)
Total Marks secured by the Student is(115)

In Scala, we will have to explicitly specify null as a parameter since it is a functional language and all functions take in parameters. Below image shows creating an object and executing it in Scala shell.

在Scala中,我们将必须明确指定null作为参数,因为它是一种功能语言,并且所有函数都接受参数。 下图显示了创建对象并在Scala shell中执行它。

在Scala中扩展课程 (Extending a Class in Scala)

A base class can be extended which is similar to Java except for two restrictions that only the primary constructor of child class can pass parameters to the base class constructor and override keyword must be specified.

可以扩展与Java类似的基类,但有两个限制,即只有子类的主构造函数可以将参数传递给基类构造函数,并且必须指定override关键字。

Consider an example of overriding the base class method;

考虑重写基类方法的示例;

class Student(val m1:Int,val m2:Int) {
 	var total:Int = m1 + m2
	var ma1:Int = m1
	var ma2:Int = m2
 	def calculateTotal(ma1:Int,ma2:Int) {
 	total = ma1 + ma2
	println("Total is :"+total)
 	}
 	override def toString(): String = "(" + total + ")";
   }

The student is the base class which has a calculateTotal method accepting marks of two subjects and output the total marks.

学生是基础类,具有可接受两个科目的分数并输出总分数的calculateTotal方法。

Now we shall create a subclass extending the Student class which adds the marks of four subjects and calculate the grand total as shown below.

现在,我们将创建一个扩展Student类的子类,该子类将四个主题的分数相加并计算总计,如下所示。

class CollegeStudent(override val m1:Int,override val m2:Int,val m3:Int,val m4:Int) extends Student(m1,m2) {
	var ma3:Int = m3
	var ma4:Int = m4
	var tot:Int = 0;
 	def calculateTotal( ma1:Int, ma2:Int, ma3:Int,  ma4:Int) {
	tot = ma1 + ma2 + ma3+ ma4
	println("Total is :"+tot)
	}
	override def toString():String = "(" + tot + ")";
}

We are adding “override” keyword to variables m1 and m2. The keyword “extends” is used to extend the base class Student. But the method is not overridden since the implementation has a different definition.

我们将“ override”关键字添加到变量m1和m2。 关键字“ extends”用于扩展基类Student。 但是由于实现具有不同的定义,因此不会重写该方法。

Create an object ColStud of CollegeStudent class as;

创建一个CollegeStudent类的对象ColStud作为;

object ColStud {
def main(args:Array[String]) {
val total = new CollegeStudent(72,65,85,60);
total.calculateTotal(72,65,85,60);
println("Grand Total Marks of the Student is"+total)
}
}

Run the above code by executing the below command;

通过执行以下命令运行以上代码;

scala> ColStud.main(null)
Total is :282
Grand Total Marks of the Student is(282)

Scala中的Singleton对象 (Singleton Objects in Scala)

There is no static keyword in Scala, instead we have singleton objects. All we need is to use object keyword to create a singleton object. We can call it’s methods directly, we can’t pass parameters to its primary constructor. Below is a quick example of singleton objects in Scala.

Scala中没有static关键字,相反,我们有singleton对象 。 我们需要做的就是使用object关键字创建一个单例对象。 我们可以直接调用它的方法,我们不能将参数传递给它的主要构造函数。 以下是Scala中单例对象的快速示例。

object Test{
    def say(){
    println("Hi")
  }
}

Below image shows how to execute the above-defined method, notice how similar it is to Java static method execution.

下图显示了如何执行上面定义的方法,请注意它与Java静态方法执行的相似程度。

Scala库中的内置对象 (Inbuilt objects in Scala library)

There are many inbuilt objects in scala library one among them is the Console object which reads the values and prints on the terminal.

Scala库中有许多内置对象,其中之一是Console对象,它读取值并在终端上打印。

Lets consider an example for Console object;

让我们考虑一个Console对象的例子。

object Cons {
def main(args:Array[String]) = {
    Console.println("Enter a number :");
    val num = Console.readInt;
    Console.println("Entered Number is :"+num)
    }
}

We are creating a Cons object. In the main method, we ask the user to enter a number and read the entered number from the terminal using readInt and print the entered number.

我们正在创建一个Cons对象。 在主要方法中,我们要求用户输入一个数字,并使用readInt从终端读取输入的数字并打印输入的数字。

Run the code as shown below

运行代码,如下所示

>Cons.main(null)
Enter a number :
Entered Number is :345

Scala弃用模式 (Scala -deprecation mode)

Below image shows what happens when we define Cons object in Scala shell.

下图显示了在Scala shell中定义Cons对象时发生的情况。

Notice the warning “there was one deprecation warning; re-run with -deprecation for details”. It doesn’t tell us which line number is causing this warning, however, the object is defined. But using deprecated methods is not a good idea. So we can run Scala shell with -deprecation option and it can provide useful information to correct it. Below image shows it in action.

注意警告“有一个弃用警告; 请使用-deprecation重新运行以获取详细信息”。 它不会告诉我们哪个行号引起此警告,但是已定义对象。 但是,使用不推荐使用的方法不是一个好主意。 因此,我们可以使用-deprecation选项运行Scala shell,它可以提供有用的信息来对其进行更正。 下图显示了它的作用。

Scala中的伴侣类和对象 (Companion Classes and Objects in Scala)

An object which has the same name as that of the class object is a companion object and the class is called a companion class. For example;

与类对象同名的对象是伴随对象,该类称为伴随类。 例如;

class Student(sid:Int, sname:String){
val Id = sid
val name = sname
 
override def toString() =
this.Id+" "+" , "+this.name
}

Here we are creating a class Student with sid and sname as parameters and displaying these parameters.

在这里,我们创建一个以sid和sname作为参数的Student类,并显示这些参数。

Create the object with the same name Student with displayDetails method where we will print the details of the student. This Student object is termed as companion object since it has the same name as of the class and the Student class is termed as Companion class.

使用displayDetails方法创建一个与Student同名的对象,我们将在其中打印该学生的详细信息。 该Student对象被称为伴随对象,因为它与该类具有相同的名称,并且Student类被称为Companion类。

object Student{
def displaydetails(st: Student){
println("Student Details: " + st.Id+","+st.name);
}
}

Now create the testStud object to invoke the methods of these companion object and class as below;

现在创建testStud对象,以调用这些伴随对象和类的方法,如下所示;

object testStud {
 
def main(args: Array[String]) = {
    
var st = new Student(21,"Peter")
println(st)
    
Student.displaydetails(st)
}
}

Here we are printing the student object and invoking the displaydetails method by passing the student object st.

在这里,我们正在打印学生对象,并通过传递学生对象st来调用displaydetails方法。

Run the above code as testStud.main(null) which produces the following output;

将以上代码作为testStud.main(null)运行,产生以下输出;

scala> testStud.main(null)
21  , Peter
Student Details: 21,Peter

If you look at the above images, you will notice warning as “previously defined class Student is not a companion to object Student. Companions must be defined together; you may wish to use :paste mode for this.”

如果您查看上面的图像,您会注意到警告,因为“先前定义的班级Student不是对象Student的同伴。 伙伴必须一起定义; 您可能希望使用:paste模式。”

Notice that it’s suggesting to use paste mode, below image shows how to use paste mode to avoid this warning.

注意,建议使用粘贴模式,下图显示了如何使用粘贴模式来避免此警告。

Scala编译器 (Scala Compiler)

Before I conclude this post, I want to show you how to compile and run a class in Scala. If you notice above images, I am using Scala shell to create classes and use it, but my code will be lost as soon as I close it. So we can save Scala program in a file with .scala extension and then compile and run it.

在结束本文之前,我想向您展示如何在Scala中编译和运行类。 如果您注意到上面的图片,我正在使用Scala shell创建类并使用它,但是一旦关闭它,我的代码就会丢失。 因此,我们可以将Scala程序保存在扩展名为.scala的文件中,然后编译并运行它。

Test.scala

Test.scala

object Test{
	def main(args: Array[String]) = {
	println("Welcome to JournalDev!")
	}
}

It’s very similar to compiling and running a class in Java, as shown in below shell execution code.

这与用Java编译和运行类非常相似,如下面的shell执行代码所示。

Pankaj:~ pankaj$ scalac Test.scala 
Pankaj:~ pankaj$ scala Test
Welcome to JournalDev!

You will notice a file named Test.class created when you compile the Test class. Since Scala is entirely an object-oriented language, we will explain more concepts in the future articles.

您会注意到在编译Test类时创建了一个名为Test.class的文件。 由于Scala完全是一种面向对象的语言,因此我们将在以后的文章中介绍更多概念。

翻译自: https://www.journaldev.com/7497/scala-classes-objects-singleton-objects-companion-classes

scala 类中的对象是类

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值