scala构造器实战
父类
abstract class Event(val name:String) { var time:Long var content:String }
子类
private[spark] class BaseEvent(name: String) extends Event(name) { var id: String = _ override var time: Long = _ override var content: String = _
//从构造器 def this(id:String,name:String,time:Long,content:String){ this(name)//主构造器 this.id = id this.time = time this.content = content } //重写toString override def toString():String ={ id+","+name+","+time+","+content } }
再子类
private[spark] class AlarmEvent(name: String) extends BaseEvent(name) { var event_type: String = _ var event_level: String = _ var event_src_ip: String = _ var event_src_port: String = _ var event_tar_ip: String = _ var event_tar_port: String = _ var event_src_server_name: String = _ var event_tar_server_name: String = _ var event_group_count: Long = _ var event_group_start_time: String = _ var event_group_end_time: String = _ var event_server_name: String = _ def this(id: String, name: String, time: Long, content: String) { this(name) this.id = id this.time = time this.content = content } //构造器的继承与重载 def this(id: String, name: String, time: Long, content: String, event_type: String, event_level: String, event_src_ip: String, event_src_port: String, event_tar_ip: String, event_tar_port: String, event_src_server_name: String, event_tar_server_name: String ) { this(name, id, time, content) this.event_type = event_type this.event_level = event_level this.event_src_ip = event_src_ip this.event_src_port = event_src_port this.event_src_server_name = event_src_server_name this.event_tar_ip = event_tar_ip this.event_tar_port = event_tar_port this.event_tar_server_name = event_tar_server_name } //重载 def this(id: String, name: String, time: Long, content: String, event_type: String, event_level: String, event_src_ip: String, event_src_port: String, event_tar_ip: String, event_tar_port: String, event_src_server_name: String, event_tar_server_name: String, event_group_count: Long, event_group_start_time: String, event_group_end_time: String, event_server_name: String ) { this(name, id, time, content, event_type, event_level,event_src_ip,event_src_port,event_tar_ip,event_tar_port,event_src_server_name,event_tar_server_name) this.event_group_count=event_group_count this.event_group_start_time=event_group_start_time this.event_group_end_time=event_group_end_time this.event_server_name=event_server_name } //toString的继承重载 override def toString():String= { super.toString() +","+ event_type + "," + event_level + "," + event_src_ip + "," + event_src_port +","+ event_src_server_name + "," + event_tar_ip + "," + event_tar_port + "," + event_tar_server_name } }
执行结果:
2,1,0,3,4,5,6,7,9,80,8,00
scala语言的父类继承和重载,toString的继承重载,靠super
子类中的构造器不能够super,报错
作者:舆-风动名扬 出处:http://www.cnblogs.com/gnool/
© 作者和博客园,欢迎转载,未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如果觉得还有帮助的话,可以点一下右下角的【推荐】想跟我一起进步么?那就【关注】我吧。