- from last time we had the class BankAccount
- with methods
- withdraw, deposit, getbalance
- the bank account has a hidden balance that is only accessable via the methods.
Method Definition Syntax
public void deposit (double amount)
public void withdraw(double amount)
public double getbalance()
- these are seperated by : access specifiers (public), return type (void,double), method names (deposit, withdraw, getbalance) and method parameters [double amount, ()]
- every class representing an object requires a special method called a constructor
- the role of the constructor is to properly initialize any hidden data fields (eg. sets balance to zero as default)
- this is always executed when new instances of the class are created
- the name of the constructor method is the same as the name of the class
- constructors have no return type, not even void
- you cannot have a method w/ the same name of the class unless it is a constuctor
- Object classes contain fields of private data. Not accessible to the user or Application Programmer(AP)
- example: (Balance, account number, account holder, etc.)
Class Declaration Syntax
public class BankAccount {
//constructor declataion
// methods
//private data
}
- we can fill in the method declarations (including the constructor methods) as follows:
Class Declaration Syntax
public class BankAccount {
public BankAccount() {
//constructor statements
}
public void deposit(double parameter){
// deposit statement
}
public void withdraw(double amount){
//withdraw statement
}
public double getbalance()
//getbalance statements
}
//private declatarations
}
- what was written is the public interface of the class.
- these methods are the only way for the AP to interact w/ the class
- this forms the basis of the API
- filling in the details
- consider the private data
- private data we called Instance Fields
- fields of data for every instance of the object
- access specifier, type and name
private double balance;
private int accountnumber;
- private:
- not accessable outside the object
- not part of the public interface
- accessible to methods in the class
Public class BankAccount {
private double balance; //instance field
public BankAccount() {balance = 0;} //constructor
public void deposit (double amount) {
balance = balance + amount; // method
}
public void withdraw (double amount) {
balance = balance - amount; //method
}
No comments:
Post a Comment