scala02-2021.7.9-基础篇-this
今天有空继续研究了一下Scala,不多说上code
package chapter01 class student { var name =" "; var age =" "; val school ="辽宁林业职业技术学院"; def `print` (name:String,age:String):Unit={ println(name+" "+this.age+" "+this.school) } }
package chapter01 object HelloWorld { def main(args: Array[String]): Unit = { // println("hello world") // System.out.println("hello scala from java") val student = new student() student.`print`("何喵喵","18") } }
这段代码会因为this.age 把age 指向class下定义的 age=“ ”;
解决方案:
package chapter01 object HelloWorld { def main(args: Array[String]): Unit = { // println("hello world") // System.out.println("hello scala from java") val student = new student() student.`print`("何喵喵","18") } }
package chapter01 class student { var name =" "; var age =" "; val school ="辽宁林业职业技术学院"; def `this`(name:String,age:String):Unit={ this.name=name this.age=age } def `print` (name:String,age:String):Unit={ `this`(name,age) println(this.name+" "+this.age+" "+this.school) } }
直接曲线救国
另附方法2:
package chapter01
class student (var name:String,var age:String){
val school ="辽宁林业职业技术学院";
// def `this`(name:String,age:String):Unit={
// this.name=name
// this.age=age
// }
def `print` ():Unit={
// `this`(name,age)
println(this.name+" "+this.age+" "+this.school)
}
}
package chapter01 object HelloWorld { def main(args: Array[String]): Unit = { // println("hello world") // System.out.println("hello scala from java") val student = new student("何喵喵","18") student.`print`() } }
直接在类上解决