Thursday, August 25, 2005

Like in C and C++, one uses header files to access functions and classes outside the main file, in Java one uses packages. One uses the import statement to call the classes from the package. The classes have to be declared as public in the package to make sure that accessibility is possible in the class where it is being called. The .java files inside a package has a statement for package declaration, i.e. “package ff”, here the name of the package is ff. To make sure that the package classes are accessible outside the classes they have to be present in the CLASSPATH. CLASSPATH is an environment variable for setting the path for all possible locations where java class files can be present. If one needs to import any class from any package then one need to write the import statement. For eg. “import ff.*;” statement will import classes from the package ff.

If there is a directory named ff

Under this directory there is a file abc.java

package ff;

public class abc {
public abc() {
System.out.println("Inside class abc");
}
}


Another java file is created named a1.java

import ff.*;

class a1 {
public static void main(String args[]) {
abc a = new abc();
}
}

The file a1.java when executed will print "Inside class abc" if it finds the ff directory in its classpath.

Saturday, August 13, 2005

Static variables and methods

In Java, when a variable in a class is declared static, memory is allocated for the particular variable even when the objects are declared. They can be accessed when the objects are not created out of that particular class. In Java when memory allocation is done, there is separate memory space kept for the class itself. If there are static variables in the class then their values are stored here.

For eg.

public class abc {
static private int a;
private int b;
abc(int x,int y)
{
a=x;
b=y;
}
}

In the above class as one can access the variable a by accessing abc.a. One does not have to create an object to access them. Even as one create multiple objects of the class, the value of ‘a’ in all the objects are same since they point to the same memory location.

If there are static methods in a class, then the variables in them must be static since static methods can be called without declaring the object of the class. Due to this if there is any non-static variable in the static method and the static method is called without having declared an object then it will access a variable which does not have any memory allocated to it. In Java, the main method is always kept static since it is called without having declared any object.

For eg.

public class xyz {
static int x;
int y;
public static void main(String args[])
{
x=5;
//y=7; - error
}
xyz(int a)
{
y=a;
}
}