Supertype Instance Method References

Description

The keyword super, which is only used in an instance context, references the overridden method.

We can use the following syntax to create a method reference that refers to the instance method in the parent type.

ClassName.super::instanceMethod

Example

The following code defines a parent class called ParentUtil. In ParentUtil there is a method named append which appends two String value together.

Then a child class called Util is created and extending the ParentUtil.

Inside Util class the append method is overrided.

In the constructor of Util we create two lambda expression, one is by using the append method from Util, the other is using the append method from ParentUtil class.

We use this::append to reference the current class while using Util.super::append to reference the method from parent class.


import java.util.function.BiFunction;
//from   w w w.  ja va 2s  .co  m
public class Main{
  public static void main(String[] argv){
    new Util();
  }
}
class Util extends ParentUtil{
  
  public Util(){
    BiFunction<String,  String,String> strFunc = this::append; 
    String name ="java2s.com";
    String s=  strFunc.apply(name," hi"); 
    System.out.println(s);
    
    strFunc = Util.super::append; 
    name ="java2s.com";
    s=  strFunc.apply(name," Java Lambda Tutorial"); 
    System.out.println(s);

  }
  
  @Override
  public String append(String s1,String s2){
    System.out.println("child append");
    return s1+s2;
  }  
}
class ParentUtil{
  public String append(String s1,String s2){
    System.out.println("parent append");
    return s1+s2;
  }  
}

The code above generates the following result.





















Home »
  Java Lambda »
    Java Lambda Tutorial »




Java Lambda Tutorial