How to access the method in such a inner class?

B

Bruce Sam

/* ************************* */
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?
 
A

Andrew Thompson

On 12 Jan 2005 00:35:23 -0800, Bruce Sam wrote:

....
public class A {
public void g() {

Please indent any code posted.

....
Above program is an incomplete code.The code ...

Putting ' ' after a full stop (.) would help as well. Otherwise
sentences run together. It is harder to read them.
 
J

John English

Bruce said:
/* ************************* */
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?

In g():
B b = new B();
b.f();

-----------------------------------------------------------------
John English | mailto:[email protected]
Senior Lecturer | http://www.it.bton.ac.uk/staff/je
School of Computing & MIS | ** NON-PROFIT CD FOR CS STUDENTS **
University of Brighton | -- see http://burks.bton.ac.uk
-----------------------------------------------------------------
 
B

Bruce Sam

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

John C. Bollinger

Bruce said:
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.


John Bollinger
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top