how to initiate a method which is inside another method? [closed]

I have tested this in Java and prints the message:

class Foo {
    void bar() {
        class Baz {
            void hi() {
                System.out.println("Hi");
            }
        }
        Baz baz = new Baz();
        baz.hi();
    }
}

For non-Java programmers, this would result very odd, but is the base for anonymous classes

now I need to call methodTwo from another class

Since the Baz class is inside the bar method, you can’t use it outside this method. The only case when you can do that is when this Bar class implements a public interface (or extends a public [abstract]class) that can be consumed by the another class. For example:

interface Polite {
    void hi();
}

class Bud {
    void aMethod(Polite polite) {
        polite.hi();
    }
}

class Foo {
    void bar() {
        class Baz implements Polite {
            @Override
            public void hi() {
                System.out.println("Hi");
            }
        }
        Polite baz = new Baz();
        Bud bud = new Bud();
        bud.aMethod(baz);
    }
}

Leave a Comment