Interface: Static Methods Tutorial - Java 8+

One of the new interface features in Java 8 is the ability to incorporate static methods. Basically all the same rules of an ordinary static method in a class apply to a static method in an interface. I created an extensive two part tutorial on static methods, Static Methods Part 1 and Static Methods Part 2. If you are not familiar with a static method, please watch those tutorials because I won't be spending much time explaining how a static method works, but rather I will be demonstrating their use in an interface.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md InterfaceStatic
C:\Java>cd InterfaceStatic
C:\Java\InterfaceStatic>Notepad InterfaceStatic.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class InterfaceStatic {
    public static void main(String args[]) {
        new Mary();
        new Bobby().sellHouse();
    }
}

class Bobby implements GrandmasWill {

    @Override
    public boolean takeCareOfHoardingIssue() {
        System.out.println("Call family and sort through stuff ... no small task!");
        return true; // never ending task
    }
    @Override
    public void sellHouse() {
        int i = 1;
        while(takeCareOfHoardingIssue()) {
            System.out.println("Month "+i+" of sorting ...");
            i++;
            if (i==5) break;
        }
        System.out.println("Time to call a realtor.");
        spendInheritance();
    }
    @Override
    public void spendInheritance() {
        System.out.println("I\'m going on a vacation!\n");
    }
}

class Mary {
    static { GrandmasWill.catCareTrustFund("Mary"); }    
}

interface GrandmasWill {
    boolean takeCareOfHoardingIssue(); // decades of collections
    void sellHouse();
    public abstract void spendInheritance();

    static void catCareTrustFund(String volunteer) {
        System.out.println("Congratulations "+volunteer+", you were just awarded custody of 7 cats \nand a monthly stipend of $1000.00 for their care.\n");
    }
}


Now switch back to the command prompt (CMD) and type in javac InterfaceStatic.java and press Enter.
Now type in java InterfaceStatic and press Enter.


C:\Java\InterfaceStatic>javac InterfaceStatic.java
C:\Java\InterfaceStatic>java InterfaceStatic
Congratulations Mary, you were just awarded custody of 7 cats 
and a monthly stipend of $1000.00 for their care.

Call family and sort through more stuff ...
Month 1 of sorting ...
Call family and sort through more stuff ...
Month 2 of sorting ...
Call family and sort through more stuff ...
Month 3 of sorting ...
Call family and sort through more stuff ...
Month 4 of sorting ...
Time to call a realtor.
I'm going on a vacation!


Final thoughts

None


Tutorials