How to access the method in such a inner class?

/* ************************* */
public class A {
public void g() {
class B {
public void f() {
System.out.println("f()");
}
}
}
public static void main(String[] args) {
}
}
/* ************************** */
Above program is an incomplete code.The code I want to add is that
access the meothod of f();But I don't know how to access the method f()
in such a inner class?

Bruce Sam wrote:
> Hello John,It's not clear that what I said before,I want to access the
> method f( ) in the main( ).

Put this code, based on what John English gave you, into main():

B b = (new A()).new B();
b.f();

Or do exactly as John suggested and also put this in main():

A a = new A();
a.g();

The main method is static; you cannot invoke instance methods without an
instance to invoke it on. Furthermore, B is an inner class of A; you
cannot have an instance of B without a containing instance of A. An
alternative, then, would be to make B a static nested class and make f()
a static method of B, in which case you could simply do this from main():

B.f();

Unless this is purely hypothetical, program design considerations will
govern which approach is most appropriate, and indeed, whether invoking
B.f from A.main() is appropriate at all.

Share This Page

Welcome to The Coding Forums!

Welcome to the Coding Forums, the place to chat about anything related to programming and coding languages.

Please join our friendly community by clicking the button below - it only takes a few seconds and is totally free. You'll be able to ask questions about coding or chat with the community and help others.
Sign up now!