Tuesday, October 2, 2007

Class 2

BankAccount class* (http://rapidshare.com/files/59886458/BankAccount.java.html)
You need NETBEANS to code in Java

An object of the BankAccount class has a String as an account number, and a double indicating your balance.

void deposit (double amount)
void withdraw (double amount)
double getBalance()

A variable in Java is he name of a place to store values.
Variable names start with a lowercase letter (like methods).
Variables can only hold one type of data, so the type must be declared.

synatax: type variableName;

Examples:
- int numberOfItems;
- double price;
- String word;
- BankAccount myAccount;

Assignment operator is =

numberOfItems=37;
price = 15.99;
word = new String("abcde") or word = "abcde";

A constructor of a class object is a method of the class that has the same name as the class. It can have inputs like any other class but its description does not have a return type.

new ClassName(input)

To "call" a method to operate on an object we use the dot (.) notation

syntax: variable.method(...)

int lenght= word.length();
myAccount.deposit(10000.00);

Primitive types (int, char, double, boolean) hold values and class types (BankAccount, String, ...) references to class objects.

Class objects must be constructed using the class method called a constructor. A constructor method has the same name as the class and new returns a reference.

SomeClass someClassVariable = new someClass(...);

To access methods of the object that someClassVariable refers to, use . notation someClassVariable.aMethod(...);


Examples:

BankAccount anAccount = new BankAccount("377");
anAccount.deposit(100.0);
JOptionPane.ShowMessageDialog(null, anAccount.getBalance());
String aWord = new String("abcde");
String anotherWord = "12345";
String s= aWord + anotherWord; This equals: abcde12345
*JOP.SMD(null, "Balance is" + anAccount.Balance());
Abbreviation of JOptionPane.~

+ is the concatenation operator for the String class



Methods of the String class


int length()
char charAt(int position) where 0<=positionint indexOf(char ch) returns left most position of ch; returns -1 if ch is not there
int indexOf(String s) same as above
String substring(int frmPosition) returns the substring starting at frmPosition to the end
where 0<=frmPosition<=length


0 comments: