Putting One Class Inside Another

Although a Java program is called a class, there are many occasions when a program requires more than one class to get its work done. These programs consist of a main class and any helper classes that are needed.

When you divide a program into multiple classes, there are two ways to define the helper classes. One way is to define each class separately, as in the following example:

public class Wrecker {
    String author = "Ignoto";

    public void infectFile() {
        VirusCode vic = new VirusCode(1024);
    }
}

class VirusCode {
    int vSize;

    VirusCode(int size) {
        vSize = size;
    }
}


Caution

If more than one class is defined in the same source file, only one of the classes can be public. The other classes should not have public in their class statements. The name of the source code file must match the public class that it defines.


In this example, the VirusCode class is a helper class for the Wrecker class. Helper classes often are defined in the same source code file as the class they’re assisting. When the source file is compiled, multiple class files are produced. The preceding example produces the files Wrecker.class and VirusCode.class when compiled.

When creating a main class and a helper class, you also can put the helper inside the main class. When this is done, the helper class is called an inner class.

You place an inner class within the opening bracket and closing bracket of another class.

public class Wrecker {
    String author = "Ignoto";

    public void infectFile() {
        VirusCode vic = new VirusCode(1024);
    }

    class VirusCode {
        int vSize;

        VirusCode(int size) {
            vSize = size;
        }
    }
}

You can use an inner class in the same manner as any other kind of helper class. The main difference—other than its location—is what happens after the compiler gets through with these classes. Inner classes do not get the name indicated by their class statement. Instead, the compiler gives them a name that includes the name of the main class.

In the preceding example, the compiler produces Wrecker.class and Wrecker$VirusCode.class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.220.201