Can we create a class in a method if it is possible how to access that class?

Showing Answers 1 - 9 of 9 Answers

rajasekhar

  • Nov 9th, 2006
 

See the following example.

 

By this way we can create inner classes in methods

 

class MyOuter2 {

private String x = "Outer2";

void doStuff() {

class MyInner {

public void seeOuter() {

System.out.println("Outer x is " + x);

} // close inner class method

} // close inner class definition

MyInner mi = new MyInner(); // This line must come

// after the class

mi.seeOuter();

} // close outer class method doStuff()

} //

  Was this answer useful?  Yes

santh kumar

  • Dec 19th, 2006
 

See the following code: public class InnerClassEx { public void test(int a) { final int p=a; final class X { public void a() { System.out.println("it's statement from inner class: " +p); } // End of a() } // End of class X X x=new X(); x.a(); } // End of test() public static void main(String[] args) { InnerClassEx e=new InnerClassEx(); e.test(20); } // End of main()} // End of class InnerClassEx there is someotherway also. in that, a method calls constructor of a class which in not known.that class is called as annonymous class.

  Was this answer useful?  Yes

dileep

  • Jan 24th, 2007
 

You can create a class in a method as a normal way.That type of classes are known as "Method Local Inner Class". You can access the member variables as well as the methods of your Outer Class.You can access the variables of the method where you declare the Inner Class only after the variables decalred as "final" otherwise you will get an error.We cannot access the Method Local Inner Class outside of the method.You can create an object of the class after the declaration of the class.Consider the following ex: class MyOuter{ String str ="MyOuter"; void innerClass(){ final String s1 ="MyInner"; class MyInner{ void show(){ System.out.println(str + s1); } } MyInner mInner =new MyInner(); mInner.show(); }}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions