我在eclipse中创建了以下示例。我正在关注一个教程,它提到我可以使用print(s1.captain)
来打印队长名称。该教程希望显示kotlin
自动生成setters
和getters
。
在我的代码中,print语句不打印任何东西
主要:
fun main(args : Array<String>) {
var s1 = Stronghold1("JJ",7)
print(s1.captain)
}
据点:
abstract class Stronghold(name: String, location: String)
据点1
class Stronghold1(captain: String, capacity: Int) : Stronghold("GerMachine", "Bonn")
在Kotlin中,构造函数参数只有在标记为val
或var
时才会变为属性。在你的例子中,captain
,capacity
,name
和location
只是构造函数的参数。它们不是属性的。
要将captain
和capacity
作为属性,请将val
添加到它们:
class Stronghold1(val captain: String, val capacity: Int) : Stronghold("GerMachine", "Bonn")
// ^^^ ^^^
// add add
你可能也希望用Stronghold
做同样的事情:
abstract class Stronghold(val name: String, val location: String)
// ^^^ ^^^
// add add