Orientado a objetos
Scala es un lenguaje de programación de paradigmas múltiples (admite múltiples formas de programación)
- Paquete
- Herencia
- Polimorfismo
Definir una clase de estudiante.
class Student {
//定义学生的学号
private[this] var studentID : Int = 0;
//定义学生的姓名
private[this] var studentName : String = "";
//定义set get方法
def setStudentID(id : Int) = {this.studentID = id}
def getStudentID() : Int = studentID
def setStudentName(name : String) = {this.studentName = name}
def getStudentName() : String = studentName
}
/*
*
* @Attention object和class的名字可以不一样
* 如果一样,这个object就叫做class的伴生对象
*
* */
object Student {
def main(args: Array[String]): Unit = {
//实例化Student对象
var student = new Student
student.setStudentID(1)
student.setStudentName("Freedom")
println(student.getStudentID()+"\t"+student.getStudentName())
}
}
Definir una clase de trabajador (persona heredada)
class Person (val name : String){
def say() : String = {
"Hello "+name
}
}
//创建子类
class Employee(override val name : String, val age : Int) extends Person (name){
//重写父类方法
override def say(): String = {
"Hello "+name+" ,his age is "+age
}
}
object Demo extends App {
//实例化父类对象
var person = new Person("Destiny")
println(person.say())
//实例化子类对象
var person1 = new Employee("Freedom",18)
println(person1.say())
//匿名子类
var person2 = new Person("Fate"){
override def say(): String = "hello " + name
}
println(person2.say())
}
¿Por qué puedo acceder a miembros privados?
Cuando el atributo es privado, Scala generará automáticamente el método de obtención del conjunto correspondiente. student.studentID, en realidad llamado método get
Si solo desea generar el método get sin generar el método set, puede definir el atributo como una constante
Si desea que el atributo no sea accesible externamente, use la palabra clave privada [this]
Clase interior
Dentro de la clase, defina otra clase
Definir una clase de persona.
import scala.collection.mutable.ArrayBuffer
class Person {
//定义人的姓名和年龄
private[this] var name : String = ""
private[this] var age : Int = 0
private var courseList = new ArrayBuffer[Course]()
//定义set get方法
def setName(name : String) = {this.name = name}
def getName() : String = name
def setAge(age : Int) = {this.age = age}
def getAge() : Int = age
/*
* 添加课程
* */
def addCourse(courseName : String,grade : Int): Unit ={
var course = new Course(courseName,grade)
courseList += course
}
class Course(var courseName : String,var grade : Int){}
}
object Person{
def main(args: Array[String]): Unit = {
var person = new Person
//给人添加课程信息
person.addCourse("语文",107)
person.addCourse("数学",120)
person.addCourse("英语",110)
//课程的迭代
for (c <- person.courseList)println(c.courseName+"\t"+c.grade)
}
}
Constructor de clase
1. El constructor principal: con la declaración de clase, y una inteligencia de clase tiene un constructor principal
2. Constructor auxiliar: una clase puede tener múltiples constructores auxiliares, lo que se puede lograr a través de este
class Student(var studentID : Int,var studentName : String) {
/*
*
* 辅助构造器就是一个函数,只不过函数的名字为this
*
*
* */
def this(studentName : String){
this("no studentID",studentName)
println("这是一个辅助构造器")
}
}
object Student {
def main(args: Array[String]): Unit = {
//使用主构造器实例化Student对象
var student = new Student(1,"Freedom")
println(student.studentID+"\t"+student.studentName)
//使用辅助构造器实例化Student对象
var student = new Student("Destiny")
println(student.studentID+"\t"+student.studentName)
}
}
Clase abstracta
abstract class Person{
val name : String
val age : Int
}
class Employee extends Person {
val name : String = "Freedom"
val age : Int = 18
}
class Teacher(val name : String,val age : Int) extends Person{}
object Demo {
}
Rasgo
El rasgo puede lograr herencia múltiple
trait Car{
val name : String
val id : Int
}
trait Action{
def drive() : String
}
class Bike(val name : String,val id : Int) extends Car with Action{
override def drive(): String = "Bike's name is "+name+", the bike's number is "+id
}
object Demo3 {
def main(args: Array[String]): Unit = {
var bike = new Bike("宝马",8888)
println(bike.drive())
}
}