An object is a container of related fields (variables) and methods (functions).
Objects can execute their methods.
Objects live in memory or storage.
A class is a container of related field and method definitions. Classes live in programs.
A class can be viewed as a template for constructing objects. Objects constructed from a class are called instances of that class.
A package is a container of related classes and sub-packages.
someObject.someField;
someObject.someMethod(argument1, argument2, ...);
class SomeClass {
field1 definition;
field1 definition;
// etc.
method1 definition
method2 definition
// etc.
}
somePackage.someSubPackage.someClass
From banking\Account.java
package banking;
public class Account {
// fields:
private double balance = 0.0;
// methods:
public void deposit(double amt) {
if (0 <= amt) {
this.balance = this.balance +
amt;
}
}
public void withdraw(double amt) {
if (0 <= amt && amt <=
this.balance) {
this.balance = this.balance -
amt;
}
}
public double getBalance() {
return this.balance;
}
}
Note:
this = the object executing the method being defined
From TestAccount.java:
public class TestAccount {
public static void main(String[] args)
{
// construct two Account instances:
banking.Account savings = new
banking.Account();
banking.Account checking = new
banking.Account();
// deposit some money:
checking.deposit(2500); // payday!
// trasnfer $100 to savings:
checking.withdraw(100); // this =
checking
savings.deposit(100); // this = savings
// display checking.balance:
System.out.println(checking.getBalance());
// should print 2400.0
//
System.out.println(checking.balance); // ERROR!, balance not visible here
}
}