Comparison of polymorphism in Java and polymorphism in Scala

Java

  • Java polymorphic properties are statically bound (compiler binding), and methods are dynamically bound (runtime binding). At runtime, the property outputs the value of the parent class, and the method runs the method of the subclass. That is, compile and look at the left, and run and look at the right .
  • Java polymorphism cannot access properties and methods specific to subclasses.

Scala

  • Scala polymorphic properties and methods are dynamically bound. At runtime, properties and methods are all subclassed.
  • Java polymorphism also cannot access the unique properties and methods of the subclass.

Java code

public class Java02_Dynamic {
    
    
    public static void main(String[] args) {
    
    
        Person02 t = new Teacher02();

        // Java中属性是静态绑定(编译期绑定)
        System.out.println(t.name);     // person

        // 不能访问子类特有的方法和属性
        // t.addr
        //t.sleep();

        // java中方法是动态绑定(运行期绑定)
        t.hello();      // Teacher hello
    }
}

class Person02 {
    
    
    String name = "person";
    int age = 18;

    public void hello() {
    
    
        System.out.println("Person hello");
    }
}

class Teacher02 extends Person02 {
    
    
    String name = "student";
    String addr = "China";

    @Override
    public void hello() {
    
    
        System.out.println("Teacher hello");
    }

    public void sleep() {
    
    
        System.out.println("techer sleep");
    }
}

Scala code

object Scala02_Dynamic {
    
    
  def main(args: Array[String]): Unit = {
    
    
    // scala中多态必须手动指定类型
    val t: Person02 = new Teacher02
    println(t.name)   // teacher
    // 可以直接访问父类中的非私有属性
    println(t.age)    // 18
    // scala中都是动态绑定(运行期绑定)
    t.hello()   // hello teacher
    // 同样不能访问子类特有的属性和方法
    // t.addr
    // t.sleep()
  }
}

class Person02 {
    
    
  val name: String = "person"

  var age:Int = 18

  def hello(): Unit = {
    
    
    println("hello person")
  }
}

class Teacher02 extends Person02 {
    
    

  override val name: String = "teacher"
  var addr = "China"

  override def hello(): Unit = {
    
    
    println("hello teacher")
  }

  def sleep(): Unit = {
    
    
    println("teacher sleep")
  }
}

Guess you like

Origin blog.csdn.net/FlatTiger/article/details/114524653