Type checking and conversion in scala

In scala, to test whether an object belongs to a given class, you can use the isInstanceOf method. Use the asInstanceOf method to convert a reference to a subclass reference, which is equivalent to java coercive type conversion. classOf is used to obtain the class name of the object.
In fact, the greatest value of type checking and conversion is that it can determine the type of the incoming object, and then convert it to the corresponding subclass object .

Insert picture description here

object typeConverse03 {
    
    
  def main(args: Array[String]): Unit = {
    
    
     val animal = new Animal
     val dog = new Dog
     val cat = new Cat
     testEat(dog) //向上转型 (多态)
     testEat(cat)
     testEat(animal)
     println("**************")
     println(classOf[Animal])
  }

  def testEat(a : Animal): Unit ={
    
    
    if(a.isInstanceOf[Dog]){
    
    
      println(a.asInstanceOf[Dog])
      // 这里需要注意a.asInstanceOf[Dog]对a的类型没有任何变化,而是返回的是Dog
      a.asInstanceOf[Dog].eat()
    }
    else if(a.isInstanceOf[Cat]){
    
    
      a.asInstanceOf[Cat].eat()
    }else{
    
    
      a.eat()
    }
  }
}

class Animal{
    
    
  var name = "tom"
  def eat(): Unit ={
    
    
    println(name + " feel very hungry")
  }
}
class Dog extends Animal{
    
    
  override def eat(): Unit = {
    
    
    println(name + " like eat bone")
  }
}

class Cat extends Animal{
    
    
  override def eat(): Unit = {
    
    
    println(name + " like eat fish")
  }
}

operation result

com.mo.chapter07.myextends.Dog@1888ff2c
tom like eat bone
tom like eat fish
tom feel very hungry
**************
class com.mo.chapter07.myextends.Animal

Guess you like

Origin blog.csdn.net/weixin_44080445/article/details/108908120