Saturday, February 28, 2009

3 - Class Structure

Lets begin our discussion by refreshing our memory with hello world application. A simple one class program :
public class HelloJava // The class declaration
{

public static void main(String args[]) //The main method declaration
{
System.out.println("Hello Java : a cup of arabica and robusta blend");
}

}

Inside the program we have :
1.class declaration.
2.method declaration
3.Some comments

Every class inside our application must be declared. A Declaration is like telling the world that this class exists. By convention, class names begin with a capital letter, and usually I use uppercase letter for every word that is part of a class name. Lets disect our HelloJava class :
1.syntax for class declaration is [access_modifier] class class_identifier
2.access_modifier determines the accessibility of other classes to this class. Our access modifier is public so that this class is visible and accessible to other class
3.class identifier or better known as class name is HelloJava. Our class name is HelloJava.
4.Every java program must have one main() method. Our method is declared inside HelloJava class. Our main method comprises only one statement : System.out.println("Hello Java : a cup of arabica and robusta blend"). This statement will be executed during runtime.
5.In HelloJava we haven't got any variables yet.

Comments is good for documenting our logic of programming. Comments inside a java program takes the form of :
1.//. This type of comment may spans only one line of comments
2.Traditional comment just like in c language : begin with /* end with */. This type of comments may span several lines of comments.

Until now we haven't got any variable declaration. Now lets have a look at another examples : Triangle. We have two variables, which are public. base and height are public. It means they can be accessed and manipulated by another class.

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);
}

}

Another interesting declaration is the method : showTriangle. It is public but it has a key word void. It means ON COMPLETION IT DOES NOT RETURN ANY VALUE. It has 3 statements that will be executed during run time.