Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

A variable that stores a method

Recently, I've discovered you can store a method in a variable, however when i tried to do it, It gave me an illegal start of expression, any ideas why?

    public class HelloWorld{
        public static void main(String []args){
            System.out.println("Hello World");
            Bob nBob = new Bob();
            nBob.method();
         }
    }

    class Bob{
        void methodTwo(){
            System.out.println("Check");
        }

        void method(){
            void check =  methodTwo(); //Something is wrong here
        }
    }

1 Answer

"The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void." https://docs.oracle.com/javase/8/docs/api/java/lang/Void.html

void is used for methods like "public void test(){}"...void just means "this method does not return a vlue"

ALSO: You dont "store a method in a variable"...you just store the return value of that method in a variable. For example

int test = somecalculation();

This just means, that the compiler will run somecalculation() when you declare and assign the varaible test. It just jumps to that method. And test justs gets the return value of the method somecalculation().