Monday, December 26, 2011
A Java program with two classes
class Room
{
float length;
float breadth;
void getdata(float a, float b)
{
length=a;
breadth=b;
}
}
class RoomArea
{
public static void main(String args[])
{
float area;
Room room1 = new Room();//Create an object room1 from the class Room
room1.getdata(15,20);
area=room1.length * room1.breadth;
System.out.println("Area = "+area);
}
}
A Simple Java Program
class Sample
{
public static void main(String args[])
{
System.out.println("Java is pure OOP");
}
}
Now Understanding the program
The first line
class Sample
declare a class, which is an object oriented construct. Java is a pure object oriented language so everything in java must be placed inside a class. class is a keyword and used to declare a new class definition. Sample is a java identifier that specifies the name of the class to be defined.
The Braces { & }
In java every class definition begins with an open brace “{“ and end with a matching closing brace “}” just like in C++. But 1 thing to remember , in C++ class definition ends with a semicolon “;” but in java it’s not.
For example
In C++
class SampleCPPclass
{
//Body of the class
};//Semicolone required
In Java
class SampleCPPclass
{
//Body of the class
}//Semicolone not required
The main method
The line “public static void main(String args[])” defines a method named main. This is similar to the main() function in C/C++. Every Java program must include the main method because this is the entry point for the interpreter to begin the execution of the program. But the Java Applets will not use the main method.
Now the keywords public, static & void
public : The keyword public is an access specifier that declares the main method as unprotected so it can accessible to all other classes.
static: The keyword static declares main method as one that belongs to the entire class and not a part of any objects of the class. In Java the main method must always declared as static since the Java interpreter uses this method before any objects are created.
void : The keyword void is a type modifier states that the main method does not return any value.
The Output Line
The line “System.out.println("Java is pure OOP");” is similar to the printf() statement of C or cout<< construct of C++. Since Java is a pure OOL, every method must be a part of an object. Here the println() method is a member of the out object, which is a static data member of System class.
This program will print the string “Java is pure OOP”