Scala快速入门(四)——继承、接口
Scala快速入门(四)——继承、接口
一、继承
1.继承的概念:省略
2.模板:
class Person(n:String,a:Int) {
var name:String=n
var age:Int=a
def showInfo():Unit={
println("学生信息如下")
println("名字:"+name)
println("年龄:"+age)
}
}
class Student(n:String,a:Int) extends Person(n,a){
def study():Unit={
println(this.name+". Im learning scala. ")
}
}
3.方法的重写
直接在方法之前用override进行修饰
案例:
class OverRideTest {
def print(): Unit ={
println("print")
}
}
class ExtendOver extends OverRideTest {
override def print(): Unit = {
println("aaa")
}
}
object Over{
def main(args: Array[String]): Unit = {
val ex=new ExtendOver
ex.print()
}
}
二、关于类和强制转换
1.获取Class对象
Java中,获取String的Class对象
Class clazz=String.class
Scala中
val clazz=classOf[String]
2.关于obj.isInstanceOf[T]类似Java中obj instanceof T
println("".isInstanceOf[String])
3.关于强制转换obj.asInstanceOf[T]类似Java中的(T)obj
println(1.0.asInstanceOf[Int])
三、抽象类
抽象类中有抽象字段也有普通字段,抽象类中只有抽象方法,下面是一个案例
abstract class Animal{
var name:String
var age:Int
def toString()
}
类的实现
class Dog extends Animal{
override var name: String = (){
println("")
}
override var age: Int = _
}
四、匿名子类
假设只会在本类使用到这个类的方法,那么我们可以使用匿名子类功能
val animal=new Animal(){
var name:String=_
var age:Int=_
override def toString(): Unit ={
println("prprpr")
}
}
五、接口
trait为接口,接口实例
trait talk{
def say(): Unit ={
println("say")
}
}
trait loud{
def hey(): Unit ={
println("hey")
}
}
class Test extends loud with talk{
def test: Unit ={
println("test")
}
}
object run{
def main(args: Array[String]): Unit = {
val t=new Test
t.hey
t.say
t.test
}
}
六、case class
class Dog(name:String,age:Int){}
object run{
def main(args: Array[String]): Unit = {
val hashiqi=new Dog("hashiqi",1);
val hashiqi2=new Dog("hashiqi",1);
println(hashiqi==hashiqi2)//false
println(hashiqi.equals(hashiqi2))//false
}
}
把class改成case class,那么比较都为true
七、迭代器
object run{
def main(args: Array[String]): Unit = {
val tup:(Double,Int,String,Boolean,Char)=(1.0,88,"abc",false,'a')
val iter:Iterator[Any] = tup.productIterator
val res=iter.map((x)=>{
x match {
case o:Int=> println(s"${o+1}")
case "abc"=> println("99")
case _ => println("??")//相当于default
}
});
while(res.hasNext) res.next()
}
}
八、偏函数
限定传入值进行分类处理
object run{
def main(args: Array[String]): Unit = {
def xxx:PartialFunction[Any,String]={
case "Hi" => "hello"
case x:Int=> s"$x.. is int"
case _ => "none"
}
println(xxx(444))
}
}
九、隐式转换
object run{
def main(args: Array[String]): Unit = {
implicit val a="aaa"
def aaa(implicit name:String):Unit={
println(name)
}
aaa//隐式吧上面的变量传进来
}
}