Saturday, February 28, 2009

2 - Multiclass Java Program

Now it is time for us to write application (simple one) with more than one class. The specification for our application is that we have a class that create an instance of another class. Our main class is called TriangleCreator, and the other class is called Triangle. TriangleCreator will create an instance of a Triangle.

The scenario for building such program is that we need to have a class that will be used by another class. The first class we need to write is Triangle class, the class that creates another class is called TriangleCreator. Now we have class Triangle that is depicted bellow :

public class Triangle

{


public float base = 0;
public float height = 0;

public void showTriangle()
{
System.out.println("Base : " + base);
System.out.println("Height : " + height);
System.out.println("Area : " + base*height/2);
}

}

what you have to do is the same with the other exercises we have done before :
1.Copy the source code.
2.Paste it into your text editor.
3.Save the program as Triangle.java IN YOUR WORKING DIRECTORY.

Next we need to have TriangleCreator class.

public class TriangleCreator
{

public static void main(String args[])
{
Triangle oTriangle;
oTriangle = new Triangle();
oTriangle.base = 10;
oTriangle.height = 10;
oTriangle.showTriangle();
}

}

Here is a list of action you need to do :
1.Copy the source code.
2.Paste it into your text editor.
3.Save the program as TriangleCreator.java IN YOUR WORKING DIRECTORY.
4.Compile the program using this command :javac TriangleCreator.java
5.After completing compilation process, a bytecode is produced : TriangleCreator.class
6.You run your program by executing this command : java TriangleCreator

In the next section we are going to discuss what we have done, discussing the syntax of making class.