Scope: Calling the Complex Class From External Classes

Until now we’ve stored almost every program in a single file. This becomes unwieldy as programs grow large. It becomes impossible to manage when more than one person is working on a program. It also loses out on one of the key benefits of OOP, code reusability. As long as all the code for a program is stored in one file, you can’t reuse code except by cut and paste, just like in a non-object oriented language.

There has been some code that hasn’t resided in our source files. Remember all those import statements at the top of every file? What they do is pull in prewritten and precompiled code from various locations so we can use it in our programs. You can do the same thing with classes you write. However to do this you do need to be aware of several conventions and restrictions.

1. No file should contain more than one public class. This means that our Hello World, Goodbye World example is no longer valid because each of the classes was public.
2. All files should have the same name as their single public class followed by the extension “.java”.
3. Source code files should be stored in the same directory as their compiled .class file. This is so the Java compiler can find the appropriate definitions and interfaces for a class when the class is referred to in a different file.
4. Source code and .class files should be in a directory that’s part of the $CLASSPATH environment variable.

We’ll demonstrate this by splitting the example of the previous sections into two separate files, each of which contains one class. Begin by creating a file that contains the Complex class. (Your complex file may be a little different depending on how you answered the exercises in the previous sections.) Save this file as Complex.java.

Next save the examples from the previous exercises in a separate file called ComplexExamples.java in the same directory as Complex.java. Now compile both files and run Complex Examples.java.

Comments are closed.