Lecture 2.2 - Class and Object
Lecture 2.2 - Class and Object
1. Class definition
2. Object definition
3. Defining a Class
4. Defining Instance Variables
5. Defining Instance Methods
6. Instance Methods Visibility
7. Instance Methods body
8. Returning value from a method
9. class as a type
10. Initializing object reference
11. Invoking instance method
12. Constructor
13. Converting a c++ code to java
Class and Object
Class definition
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.
Employee anEmployee;
if (anEmployee == null){
//
}
Initializing Object References - new
To initialize an object reference, you must assign it the address of an object
The new operator creates a new instance and returns the address of the newly
created object
new allocates memory for the object
new also invokes a method on the object called a constructor
new returns the address of the memory allocated for the object.
Employee anEmployee;
objectReference.methodName(parameters);
When a method invocation is made, any parameters included in the invocation are
passed to the method
All parameters are passed by value. i.e, a copy is made
The value of fundamental data types are copied
The value of object references (i.e, memory addresses) are copied
• Parameters become available within the method. They are not known outside the
method.
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.
public BankAccount()
{
}
public BankAccount(int anAccountNumber)
{
accountNumber = anAccountNumber;
}
}
Constructors