Instance Method References with Class Name

Java-Instance Method References with Class Name

Instance Method References with Class Name

It is also possible to handle a situation in which you want to specify an instance method that can be used with any object of a given class, not just a specified object. In this case, you will create a method reference as ClassName::instanceMethodName. The name of the class is used instead of a specific object, even though an instance method is specified. With this form, the first parameter of the functional interface matches the invoking object and the second parameter matches the parameter specified by the method.

Following program is an example. It defines a method called compareSpeed( ) that compare the speed of Car that print the condition defined by the trueORfalse( ) method of the Test functional interface. Car has an instance method isSameSpeed( ). This method returns true if the speed of the invoking object is same that of the passed object. This method has a parameter of type Car and returns a boolean result. Thus, is compatible with the Test functional interface because the invoking object type can be mapped to the first parameter of trueORfalse( ) and the argument mapped to trueORfalse( )’s second parameter. Thus, when the expression Car::isSameSpeed is passed to the compareSpeed( ) method, an instance of the functional interface Test is created in which the Car type of the first parameter is that of the invoking object of the instance method. The type of the second parameter is also Car because that is the type of the parameter to isSameSpeed( ).

Program

Instance Method References with Class Name

Program Source

interface Test {

    boolean trueORfalse(Car a,Car b);
}
class Car {
    
    private int speed;
    
    Car(int sp) {
        
        speed=sp;
    }
    boolean isSameSpeed(Car two) {
        
        System.out.println("speed : "+speed);
        System.out.println("two.speed : "+two.speed);
        return speed==two.speed;
    }
}
class Javaapp {

    static void compareSpeed(Test t,Car a,Car b) {
        
        System.out.println(t.trueORfalse(a, b));
    }
    public static void main(String[] args) {
        
        compareSpeed(Car::isSameSpeed,new Car(80),new Car(80));
    }
}

Leave a Comment