How a source file contain more than one class declaration in Java?

CWC
3 Min Read

The goal of including multiple classes in a single source data file is to bundle related support functionality (internal data structures, support classes, etc) together with the key general population class. Note that it usually is OK not to do this–the only effect is on the readability (or not) of your code.

example:

// This is the content of X. java
class Y {
void i() System.out.println("!!!");
}
class Z . {
public static void main(String[] args)
{
new Y().i();
}
}

The exception is each time a class is best implemented using one or more small helper classes. Usually, the code is easiest to follow when those classes are present in the same document. For instance, you might need a tiny ‘tuple’ wrapper class to some data between method calls. An additional example are ‘task’ classes implementing Runnable or Callable. They may be so small that they are best combined with parent school creating and calling them.

Why does Java support class nesting?

Java won’t have to support category nesting. In fact, if you study the Interior Classes Specification document, you will discover workarounds to class nesting. However, there have reached least two benefits to Java’s support for class nesting:

  • – An improvement in source code quality
  • – A reduction in name conflicts

Source code quality boosts with class having their nests because you declare a class closer to those objects it must change and enable that class’s methods to directly access target fields and give us a call at thing methods — even private fields and methods — of enclosing classes. To understand that benefit, look at a scenario in which a program must iterate over an array of Task objects that exist within an Employee object

Java divides nested classes into two main categories: nested top-level classes and internal classes. Furthermore, Java splits inner classes into the instance inner class, local inner class, and confidential inner class categories. To understand nested classes, you must know each category. We commence exploring those categories by focusing on nested top-level classes.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version