Java Class and Objects
Java Class and Objects
Java Class and Objects
The objectives of this chapter are: To discuss important aspects of the software development process To define objects and classes
To understand object models and class models
One of the primary reasons for the software crisis is that the complexity of the required systems has outstripped the complexity management capabilities of structured (procedurally based) software paradigms.
The average programmer takes 6 months to 2 years to learn the O-O paradigm.
There are, generally speaking, no short-cuts Review your progress! Keep all the code you've written and review Requires abstract thinking Most students report a time when, "the light goes on" The "a-ha" experience
Objects are identified from the real world An object model is created to represent the real world
The data associated with each object are identified and modelled. The various behaviours of each object are identified and modelled. Interactions between objects are modelled.
Creating Classes
Objects in the object model are formalized
Objects are abstracted into classes Only attributes and methods relevant to our domain are classified. Attributes are formalized into instance variables Behaviour is formalized into methods Classes are represented on a class diagram
Classes and the class diagram represent the static structure of the system
How the system behaves is not represented by this model.
Debit
Account
Credit
Transaction
Debit
Transaction
Credit
Ledger
Account
Debit
Credit
Transaction
Debit
Account
Credit
Transaction
Ledger
-name:String +newAccount():boolean +closeAccount(): void +newTransaction(): void
1 1..*
Account -number:int
-owner:String -overdraftLimit:int -startDate:Date +findTransaction(): Transaction +close(): boolean
1 Debit 1..* 1..* 1 Credit
Transaction
-date: Date -amount: int +getDebitAccount(): Account +getCreditAccount(): Account
Defining Classes
A class definition must have the following:
The keyword "class" followed by the name of the class The class body
Instance Variables:
public class Employee { String name; int salary; Date startingDate; [... more variable definitions ...] public int getSalary() { return salary; } public int computeHourlyRate() { // calculate hourly rate from salary } [... more method definitions ...] }
Methods:
Encapsulation
Encapsulation is a very important O-O concept
Each object has 2 views. An internal view and an external view
Encapsulation Example
Class Definition:
public class Account { private int number; private int overdraftLimit; private Date startDate; private String owner; [... methods ...]
Instances:
May 1, 2001
Fred Jones
}
Instance variables are encapsulated. - no direct access from outside the object Each object has its own variables. These variables are declared within the class.
Billy Wiggs
If a method is part of the class's public interface (external view), the method should be public If a method is part of the class's internal implementation (ie, support method, etc), it should be private. Be careful using default or protected. Use only when justified.
Classes as types
When a class is defined, the compiler regards the class as a new type. When a variable is declared, its type can be a primitive type or "Class" type.
Any variable whose type is a class is an object reference. The variable is a reference to an instance of the specified class. The variables holds the address (in memory) of the object.
int x;
Employee anEmployee;
null
Note: null means refers to no object
null References
null means refers to no object" Object references can be compared to null to see if an object is present or not. null is the default value of an object reference before it is initialized
Employee anEmployee; [...] if (anEmployee == null) { }
Parameters become variables within the method. They are not known outside the method.
public float calculateInterestForMonth(float rate) { return lowBalanceForMonth * (rate/12.0); }
Overloading Methods
Java allows for method overloading. A Method is overloaded when the class provides several implementations of the same method, but with different parameters
The methods have the same name The methods have differing numbers of parameters or different types of parameters The return type MUST be the same
public float calculateInterestForMonth() { return lowBalanceForMonth * (defaultRate/12.0); } public float calculateInterestForMonth(float rate) { return lowBalanceForMonth * (rate/12.0); }
The usual name of the get method is the name of the variable prefixed with the word "get"
getName(), getAddress(), getPhone(), getBalance()
public class BankAccount { private float balance; public float getBalance() { return balance; }
The usual name of the set method is the name of the variable prefixed with the word "set"
setName(), setAddress(), setPhone(), setBalance()
public class BankAccount { private String ownerName; public void setOwnerName(String aName) { ownerName = aName; }
Whether a variable has an associated get and set method is a design issue; it is not a coding issue. Imagine a BankAccount Class
All Bank Accounts have Account Numbers
If we don't provide a set method, how do we initialize the variable in the first place?
In order to put the object into a usable state, its instance variables should be initialized to usable values
This could be accomplished by calling the various set methods This is not always possible because it is not required that all instance variables have set methods.
Java provides for another method of initializing objects When an object is created, a constructor is invoked. The responsibility of the constructor method is to initialize the object into a usable state.
Constructors
Constructors have the following characteristics
There is NO return type. NOT even void The method name is the same name as the class Constructors can be overloaded
In order to put the object into a usable state, its instance variables should be initialized to usable values
This could be accomplished by calling the various set methods This is not always possible because it is not required that all instance variables have set methods.
Java provides for another method of initializing objects When an object is created (using new), a constructor is invoked. The responsibility of the constructor method is to initialize the object into a usable state.
Constructors - Example
public class BankAccount { String ownersName; int accountNumber; float balance; public BankAccount() { } public BankAccount(int anAccountNumber) { accountNumber = anAccountNumber; } public BankAccount(int anAccountNumber, String aName) { accountNumber = anAccountNumber; ownersName = aName; } [...] }
Constructors - Example
When an object is created (using new) the compiler determines which constructor is to be invoked by the parameters passed
Multiple constructors allows the class programmer to define many different ways of creating an object.
void main(String[] args) anAccount = new BankAccount(); anotherAccount = new BankAccount(12345); myAccount = new BankAccount(33423, "Craig");
Constructors
If no constructors are defined for a class, the compiler automatically generates a default, no argument constructor
All instance variables are initialized to default values.
However, if any constructor is defined which takes parameters, the compiler will NOT generate the default, no argument constructor
If you still need one, you have to explicitly define one.
Review
What is the difference between classes and objects? What are the modifiers for classes, instance variables and methods? What do they mean? What is encapsulation? Why is it important? How are method parameters defined? How are method parameters passed? How do accessor methods support encapsulation? What are constructors?