Multiple Classes
by
, January 29th, 2012 at 04:49 PM (1105 Views)
In each Java application, you're going to have a series of classes containing various instructions for the compiler. Each class can be responsible for different actions or functionality of the program.
Below is our first class, appropriately named class1.
Let's say that class1 is responsible for a few introductory things, such as a welcome message and lastly referencing the other classes into action. That's often the main role of the first class, to call other classes and execute code from within them. Below is our second class.
public class class2{ public void class2Method(){ System.out.println("This code is executed via class2!"); } }
Right now we have two separate classes. We can use class1 fine, but if we want to access class2, we're going to need to say so in class1, since that is our main class containing our main method. We can do this by adding some code to class1.
We've added two new lines of code to class1.
class2 class2Object=new class2(); class2Object.class2Method();
The first line creates a class2 object we can use to implement methods from within that class. To create this object, you must first write the class name (in our case, it's class2). Then, you must write the name of the object you'd like to use to reference that class, it can be anything. I've kept it simple with class2Object. And lastly, write =new because we're creating a new object, followed by the name of the class once again (class2). This is shown above for your reference.
We now have a class2 object we can use to execute methods from within the second class. To actually do this, you must write the object name, followed by a dot separator, followed by the name of the method from within that class (class2Method). Your application will now execute everything from within that method of that class.