首先新建一个Student类
定义类中属性的名称、类型,类中定义一个printInfo方法
引入伴生对象
对alice和bob进行实例化,并调用printInfo方法打印其信息
运行一下
class Student(name: String, age: Int) {
def printInfo(): Unit = {
println(name + " " +age+" " +Student.school)
}
}
//引入伴生对象
object Student{
val school: String = "XY"
def main(args: Array[String]): Unit = {
val alice = new Student("alice", 20)
val bob = new Student("bob", age = 23)
alice.printInfo()
bob.printInfo()
}
}
方法调用成功