Object and Static Methods in Java

Why are Public Instance Variables Bad?

Using public instance variables is considered to be bad form in object oriented programming because they are dangerous. If anyone in the world can change the value of an instance variable, debugging is difficult. It is better to restrict access to instance variables by making them private. Access to instance variables can then only be accomplished using accessor methods ("getters") to obtain information and mutator methods ("setters") to modify information.

Object Methods

An object method, usually just called method, is used for manipulating the instance variables in an object. Here is the syntax:

public returnType methodName(type1 param1, type2 param2, ...)
{
    bodyOfMethod
    return returnValue
}

Note:   In C++, the syntax for a variable header is
public returnType className::methodName(type1 param1, type2 param2, ...)
because all methods are global in C++. In Java, a simpler syntax is possible because each method is defined within the class to which it belongs.

Example 1:

public class Kid
{
    // Private instance variables.
    private String name;
    private long id;
    private char gender;
    private int age;

    // Other methods including constructor go here.

    // Accessor method for age.
    public int getAge()
    {
       return age;
    }

    // Mutator method for age.
    public int setAge(int a)
    {
       age = a;
    }
}

Static Methods

A method that does not belong to a particular object, but rather to the class itself is called a static method. (The term static is not a particularly good one, but is a holdover from C and C++ terminology.) Whereas object methods require an instance of an object to be legally called, static methods can be invoked directly from the class. Here are some Examples of static method calls:

Math.pow(2.0, 16.0);
JOptionPane.showMessageDialog(null, "Hello");
name = JOptionPane.showInputDialog("Enter your name.");
x = Keyboard.getInt();

The main method itself is a static method that is invoked automatically when the application is run.

Static Instance Variables

A static instance variable belongs to the class rather than to a specific object. There is only one copy of a static variable, no matter how many objects of that class exist. This makes static variables useful for creating serial numbers: everytime a new object is created, add one to the static serial number variable.

Here are some other examples of a static instance variables:
Math.E
Math.PI
Integer.MAX_VALUE
Integer.MIN_VALUE

IMPORTANT RULE: A static method f can only call other methods or use variables if they are also static, unless the object to which those methods or variables belong has been created in the static method f. See the Example functions in Day2.