Sunday, February 28, 2021

A complete sample for binding variable usage

Below is a complete sample code illustrating the usage of binding variables with instanceof operator

In the below code, we have an interface Pet which is implemented by two record classes - Cat & Dog. Dog has an instance method bark() and Cat has an instance method meaw().

In the main() method of the Main class, we proceed to create Pet instances for Dog and Cat and proceed to show usage of instanceof operator with & without the usage of binding variable


interface Pet {
    default public String color() {
        return this.color();
    }
}

record Dog(String color) implements Pet {

    public void bark() {
        System.out.println("I bark...");
    }
}

record Cat(String color) implements Pet {

    public void meaw() {
        System.out.println("I meaw...");
    }
}

public class Main {

    public static void main(String[] args) {

        Pet p1 = new Dog("White");
        Pet p2 = new Cat("White");

        // Without using binding variable
        if (p1 instanceof Dog) {
            Dog d = (Dog) p1;
            d.bark();
        }

        // With binding variable
        if (p2 instanceof Cat c) {
            c.meaw();
        }
        
    }
}


Sample code used in this post can be downloaded from https://github.com/ashokkumarta/awesomely-java/tree/main/2021/02/Language-Features/Instanceof-Binding-Variable/A-complete-sample

No comments:

Post a Comment