Use of Class Definitions Inside a Method in Java

Use of class definitions inside a method in Java

This is called a local class.

2 is the easy one: yes, a class file will be generated.

1 and 3 are kind of the same question. You would use a local class where you never need to instantiate one or know about implementation details anywhere but in one method.

A typical use would be to create a throw-away implementation of some interface. For example you'll often see something like this:

  //within some method
taskExecutor.execute( new Runnable() {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
});

If you needed to create a bunch of these and do something with them, you might change this to

  //within some method
class myFirstRunnableClass implements Runnable {
public void run() {
classWithMethodToFire.doSomething( parameter );
}
}
class mySecondRunnableClass implements Runnable {
public void run() {
classWithMethodToFire.doSomethingElse( parameter );
}
}
taskExecutor.execute(new myFirstRunnableClass());
taskExecutor.execute(new mySecondRunnableClass());

Regarding interfaces: I'm not sure if there's a technical issue that makes locally-defined interfaces a problem for the compiler, but even if there isn't, they wouldn't add any value. If a local class that implements a local interface were used outside the method, the interface would be meaningless. And if a local class was only going to be used inside the method, both the interface and the class would be implemented within that method, so the interface definition would be redundant.

Class definition inside method argument in Java?

It's creating an anonymous class.

Note that within anonymous class, you can refer to final local variables from within the earlier code of the method, including final parameters:

final String name = getName();

Thread t = new Thread(new Runnable() {
@Override public void run() {
System.out.println(name);
}
});
t.start();

The values of the variables are passed into the constructor of the anonymous class. This is a weak form of closures (weak because of the restrictions: only values are copied, which is why the variable has to be final).

Can we have an inner class inside a method?

Yes you can.

public final class Test {
// In this method.
private void test() {
// With this local variable.
final List<String> localList = new LinkedList<String>();
// We can define a class
class InnerTest {
// Yes you can!!
void method () {
// You can even access local variables but only if they are final.
for ( String s : localList ) {
// Like this.
}
}
}
}

}

Class Inside Method

can I create object of my class from main method and How?

No. Only the met method knows anything about the class. If you want to use the class outside that method, you should declare it either as a nested class within Demo, or as a completely separate non-nested class.

Personally I would try to avoid nested classes as far as possible - they have odd restrictions, you can often end up creating inner classes instead of nested classes by accidentally forgetting the static modifier, and they're generally a pain.

Convention on Classes Inside Methods

This is called a local class. From Java Docs:

You can define a local class inside any block (see Expressions, Statements, and Blocks for more information). For example, you can define a local class in a method body, a for loop, or an if clause.

A local class has access to the members of its enclosing class... However, a local class can only access local variables that are declared final.

Why the main program in Java is put into a class?

The Java Virtual Machine (JVM) has to start the application somewhere. As Java does not have a concept of “things outside of a class” the method that is called by the JVM has to be in a class. And because it is static, no instance of that class is created yet.

What's the use of a method-local inner class?

Using method-local classes can increase the readability of your code by keeping related parts together. As a contrived example, suppose you have a method that needs to create a thread to do something in the background:

class Test {
void f() {
// Method local inner class
class InnerClass {
private String myThreadName;
// InnerClass constructor
public InnerClass(String myThreadName) {
this.myThreadName = myThreadName;
}
// InnerClass method
public void run() {
Thread thread = new Thread(
// Anonymous inner class inside method local inner class
new Runnable() {
public void run() {
doSomethingBackgroundish();
}
}
);
thread.setName(myThreadName);
thread.start();
}
}
InnerClass anInnerClass = new InnerClass(aThreadName);
anInnerClass.run();
}
}

Without method-local classes, you would have to either:

  • create a new named class inside Test to do the background processing, or
  • create a new named class in a separate source file to do the background processing.

Both these options can reduce the readability of the code by moving the related processing somewhere else in your source tree (maybe in the same source file, maybe in another source file entirely). Using a method-local class keeps the processing logic right where it is used.

This is certainly not applicable for all situations, but it can be very useful in a number of common situations. Such code is commonly used for GUI action listeners, which are very small classes that usually just relay action method calls from one place to another.



Related Topics



Leave a reply



Submit