我认为一旦通过伴生对象创建了该类的对象,我就可以调用该类的方法。但我无法做到这一点。下面是我的代码:
class Employee(val id: Int, val initialBalance: Int) {
val message = println("Object created with Id: " + id + " balance: " + initialBalance)
def printEmployeeDetails = "Id: " + id + " InitialBalance: " + initialBalance
override def toString = "Id: " + id + " InitialBalance: " + initialBalance
}
object Employee {
private var id = 0
def apply(initialBalance: Int) {
new Employee(newUniqueId, initialBalance)
}
def newUniqueId() = {
id += 1
id
}
}
object testEmployee extends App {
val employee1 = Employee(100)
employee1.printEmployeeDetails //getting error, why?
println(employee1) // This line is printing (), why?
val employee2 = Employee(200)
println(employee2) // This line is printing (), why?
}
朋友们,你能帮我理解它为什么会这样吗?谢谢。