Search Java Programs

Thursday, January 7, 2010

Classes and Methods

Methods are subroutines or functions used to perform a task with or modify an object. Since classes are the base of all java structures all functions must be included in a class. There are three levels of visibility for methods, public, private, and protected. Public methods are accessible from anywhere in the program, private methods are only accessible from within the class, and protected methods are available inside the class and any subclasses in the same package. If no access is specified class and package have access but not subclasses. A method must declare the type of return value or void for no return value.

Classes may also contain class wide variables with the same public, private, protected attributes. It is usually considered best practice to set the class variables as private and use public getter and setter routines to access the variable. This is called encapsulation.
Include GetterSetterEx.java

class GetterSetterEx {
private int i = 0;
private String s = "string";

public int getI() {
return(this.i);
}

public void setI(int i) {
this.i = i;
}

public String getS() {
return(s);
}

public boolean isSLongerThanI() {
if (s.length() > i) {
return(true);
} else {
return(false);
}
}

public GetterSetterEx(int i, String s) {
this.i = i;
this.s = s;
}
}

This class simply demonstrates how to create private class variables and getter/setter methods for each. The variables are declared as private and can only be accessed from this class. When using this class in conjunction with any other class you must use the get and set methods for each variable. In addition to the getters and setters we added another simple method to determine if the string is longer than the value of the integer.

Also notice the final method in the class, and how it has the same name as the class. This is called the constructor and is called whenever the class is initialized. This method expects 2 values to be passed at initialization. The constructor method should always be declared public with no return type or void declaration. Multiple constructors can exist with different parameter types that handle initialization differently.

Importing Packages
Java uses the import command to include external packages to extend the functionality of your application. The Java Runtime Environment (JRE) includes a large set of libraries to build your application with ranging from network socket connections to graphical user interface (GUI) building packages. Before a package or class, such as the one we previously created can be used, they must be imported. The import statement comes at the beginning of the .java file and should be outside the class declaration.

No comments:

Post a Comment

Website Design by Mayuri Multimedia