Do I need to make two classes of this java program?

Is it important to save all class code as separate .java files, for example, as follows?

Outer.java, Inner.java, Test.java 

Or I can create one java file as Test.java. Please explain the anonymous class, how can we create an anonymous class in java and what is the advantage / disadvantage over the normal class?

 class Outer { private int data = 50; class Inner { void msg() { System.out.println("Data is: " + data); } } } class Test { public static void main(String args[]) { Outer obj = new Outer(); Outer.Inner in = obj.new Inner(); in.msg(); } } 
+6
source share
3 answers

An anonymous class in Java is a class that is not named, and is declared and created in a single expression. You must use an anonymous class whenever you need to create a class that will be created only once.

Although an anonymous class can be complex, the syntax for declaring an anonymous class makes them most suitable for small classes that have just a few simple methods.

An anonymous class should always implement an interface or extend an abstract class. However, you do not use the extension or implement the keyword to create an anonymous class. Instead, you use the following syntax to declare and instantiate an anonymous class:

 new interface-or-class-name() { class-body } 

Inside the body of the class, you must provide an implementation for each abstract method defined by the interface or abstract class. Here is an example that implements an interface called runnable that defines a single method called run:

 runnable r = new runnable() { public void run() { //code for the run method goes here } }; 

Here are a few other important facts about anonymous classes:

  • An anonymous class cannot have a constructor. Thus, you cannot pass parameters to an anonymous class when you create it.

  • An anonymous class can access any variables that are visible to the block in which the anonymous class is declared, including local variables.

  • An anonymous class can also access the methods of the class containing it.

+2
source

See Codes for the Java Programming Language :

Each Java source file contains one public class or interface. When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class. The public class must be the first class or interface in the file.

I think this should answer your question. As I said in my comment, it is not recommended to write a file containing several unrelated classes. However, if you have related classes with one public class that you have in the file, you can put them in the same source file.

+4
source

yes, you can do it, but it should be in a little programming, while in a large application you need to make the class individual, Java strongly recommended making the class another file, but it is up to you.

+1
source

All Articles