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 = 0def 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 + m2var ma1:Int = m1var ma2:Int = m2def calculateTotal(ma1:Int,ma2:Int) {total = ma1 + ma2println("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 = m3var ma4:Int = m4var tot:Int = 0;def calculateTotal( ma1:Int, ma2:Int, ma3:Int,  ma4:Int) {tot = ma1 + ma2 + ma3+ ma4println("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 = snameoverride 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 类中的对象是类

scala 类中的对象是类_Scala类和对象– Singleton对象,伴侣类相关推荐

  1. scala 类中的对象是类_Scala中的类和对象

    scala 类中的对象是类 Scala中的课程 (Classes in Scala) A class is a blueprint for objects. It contains the defin ...

  2. 【Groovy】Groovy 脚本调用 ( Groovy 类中调用 Groovy 脚本 | 参考 Script#evaluate 方法 | 创建 Binding 对象并设置 args 参数 )

    文章目录 一.Groovy 类中调用 Groovy 脚本 1.参考 Script#evaluate 方法分析 Groovy 类中调用 Groovy 脚本 2.创建 Binding 对象并设置 args ...

  3. python类中包含一个特殊的变量、它表示当前对象自身_知到APP教师职场礼仪第七单元章节测试网课答案大学课后答案...

    [判断题]水参与了植物体内众多的生物化学反应. [单选题]所有参加保险的人为自己办理保险而合作成立法人组织的相互保险组织是( ). A. 相互保险公司 B. 相互保险社 C. 保险合作社 D. 保险合 ...

  4. java定义一个点_JAVA 定义一个Point类 它的对象是指一个平面上的点(x,y),在定义Point类中要定义它的三个构造函数...

    JAVA 定义一个Point类 它的对象是指一个平面上的点(x,y),在定义Point类中要定义它的三个构造函数 JAVA 定义一个Point类 它的对象是指一个平面上的点(x,y),在定义Point ...

  5. python类中包含一个特殊的变量、它可以访问类的成员_区域联防的运用中遵循并贯彻以球为主的防守原则,做到球人区三者兼顾。( )...

    刘墉书法的特点是用墨厚重,体丰骨劲,浑厚敦实,别具面目.A:对B:错 Python类中包含一个特殊的变量(),它表示当前对象自身,可以访问类的成员.A:meB:selfC:thisD:与类同名 在过火 ...

  6. 调用别的类中的变量(但是还是有问题)

    感觉自己确实水平太低了,下面这个函数是定义在一个属性页的类中的,这样就可以传递别的类CFIRADlg中的变量,所以前面的函数不知道可以这么写,还以为非要写在主类中,所以标定的函数全部都写在了主类中,这 ...

  7. 类中的关键字public、protected、private究竟是什么意思?

    类中的关键字public.protected.private究竟是什么意思? 这三个关键字用来修饰类中的成员的有效域,即成员在哪个域内是可被调用的.下面我们来仔细说明这句话. 所谓"类中的成 ...

  8. 类中成员函数声明后面的const的含义

    这个const一般是对类中成员函数属性的声明,但这个声明怪怪的,只能放在函数声明的尾部,大概是因为其它地方都已经被占用了.这个声明表示这个函数不会修改类中的任何数据成员.如果在编写const成员函数时 ...

  9. 【Groovy】Groovy 脚本调用 ( Java 类中调用 Groovy 脚本 )

    文章目录 前言 一.Groovy 类中调用 Groovy 脚本 1.参考 Script#evaluate 方法分析 Groovy 类中调用 Groovy 脚本 2.创建 Binding 对象并设置 a ...

最新文章

  1. 福利 | 零基础学习Python量化交易 !(深圳)
  2. 【LeetCode OJ】Remove Duplicates from Sorted List
  3. This text field does not specify an inputType or a hint
  4. Python 文件writelines() 方法和处理双层列表
  5. dva源码解析(一)
  6. python中怎样创建字典内建函数_python中常用的字典内建函数
  7. mysql数据库sql注入原理_sql注入原理详解(一)
  8. springboot整个缓存_springboot整合ehcache缓存
  9. *第十五周*数据结构实践项目一【验证哈希表及其算法】
  10. mysql中的转换类型数据类型_mysql数据类型转换
  11. php 不返回 数据,php – file_get_contents没有返回任何数据
  12. 搞深度学习如何快速读懂开源代码?
  13. WPS文字教你制作米字本即用于临摹练字的米字格
  14. google earth pro 安装后启动时报错:google 地球无法连接到登录服务器(错误代码:c000000c)
  15. java IE11浏览器文件下载的文件名乱码
  16. Latex表格排版(三个表格并列、单元格内容自动换行)
  17. Python绘制bezier曲线
  18. python讲师陈越_浙大陈越老师数据结构课件
  19. 网络安全烽火再起 BAT聚头2017 网络安全生态峰会
  20. [原]基因组变异检测概述

热门文章

  1. 三分钟免费搞定网站在线客服,利用PowerTalkBox控件制作而成,为大家提供比较好的示例...
  2. 排序1+3:基数排序(RadixSort),希尔排序(ShellSort)和快速排序(QuickSort)
  3. [转载] python while循环 打印菱形
  4. [转载] python flask实现分页
  5. 2019牛客多校 Round2
  6. 基于docker的spark-hadoop分布式集群之二: 环境测试
  7. 面向对象 之重写重载
  8. asp.net 将ppt,word转化为pdf实现在线浏览详解
  9. open_cursors参数设置调优
  10. *args和**kargs