dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
12 stars 0 forks source link

Java Virtual Method Invocation #73

Open dvas0004 opened 5 years ago

dvas0004 commented 5 years ago

A form of abstraction which allows you to deal with a superclass rather than the details of an implementation. A rather contrived example follows:


abstract class demoVMI{
    abstract void greetings(); // <---- virtual method common across all subclasses
}

class maltese extends demoVMI {

    @Override
    void greetings() {  greetingInMaltese();  } // <---- virtual method calls actual method here
    void greetingInMaltese() {  System.out.println("Bongu!");  }

}

class estonian extends demoVMI {

    @Override
    void greetings() {  greetingInEstonian();  } // <---- virtual method calls actual method here
    void greetingInEstonian() {  System.out.println("Tere!");  }

}

public class Main {

    private static void greet(demoVMI greeting){  greeting.greetings();  }

    public static void main(String[] args) {

        maltese Malteser = new maltese();
        estonian Eesti = new estonian();

        greet(Malteser);
        greet(Eesti);

    }

}

Note that in Main , the greet method does not know about the implementation-specific greetingInMaltese and greetingInEstonian methods. It just calls the virtual method greetings, which is present in both implementations because of the abstract class. Within the child classes, the virtual method greetings serves only to call the actual method providing the intended functionality