Scala anonymous inner class

1 Overview

An anonymous inner class is an unnamed subclass object that inherits a certain class, and it can be used directly to create an example object. Anonymous inner classes are used extensively in Spark's source code. After learning this piece of content, it is very helpful for us to view the underlying source code of Spark.

2. Grammar

new 类名(){
    
    
	//重写类中所有的抽象内容
}

Note: In the above format, if the main constructor parameter list of the class is empty, the parentheses can be omitted.

3. Usage scenarios

  • When the object method (member method) is called only once
  • Can be passed as a method parameter

4. Case

demand:

  1. Create an abstract class of Person and add an abstract method of employee sayHello
  2. Define a show() method, which needs to pass in an object of type Person, then call a subclass object of the Person class, and call the sayHello method of the Person class
  3. Add the main method, create a subclass object of the Person class through an anonymous inner class, and call the sayHello() method of the Person class
  4. Call show() method

Code:

object demo {
    
    
  abstract class Person{
    
    
    def sayHello();

  }

  def main(args: Array[String]): Unit = {
    
    
    //对成员方法仅调用一次:
    new Person {
    
    
      override def sayHello(): Unit = {
    
    
        println("匿名内部类的sayHello()方法被调用了!")
      }

    }.sayHello();

    //作为方法的参数进行传递:
    show(new Person {
    
    
      override def sayHello(): Unit = println("作为方法的参数进行传递sayHello()方法被调用了!")
    })
  }
  def show(person: Person): Unit ={
    
    
    person.sayHello();
  }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/zh2475855601/article/details/114690426