Top
Previous Next
Java's Object Orientation, I/O CS 161 - Java

Variables (Fields)

Instance variables

In a good object oriented Java class, just about all variables ought to be instance variables.

Each object (instance) will have its own copy of these fields

Class variables

Qualifying a variable (field) with the keyword static makes that variable a class variable:

Local Variables

Variables you declare and use only with a method or a smaller block of code.
Source: examples/SimpleBankAccount.java



/** SimpleBankAccount.java - illustrate instance and local cariables
**/
 
public class SimpleBankAccount {
 
// Instance variables
 
private String id; // these are all "instance" variables
private String name; // of associated person
private String address; // to send statements to
private long balance;
 
public SimpleBankAccount(String id, String name, String address) {
// "this" refers to "this object" or "this instance of the class"
this.id = id;
this.name = name;
this.address = address;
balance = 0; // same as this.balance = 0;
}
 
public String getName() {
return name;
}
 
public void addToBalance (long amount) {
balance = balance + amount;
}
 
public void calculateInterest () {
double interest; // local variable
interest = balance * interestRate;
balance = balance + (long) interest; // "casting"
}
 
public float getBalance() {
return balance;
}
 
private static double interestRate = .06; // class variable
 
static void setInterestRate(double newRate) {
interestRate = newRate;
}
}
 


Top
Previous Next
jwd