| Activity |
1.1 OBJECTS AND CLASSES
All objects are unique. But at the same time they are also part of a
class of objects (for example, a student is unique but he/she is also part of
the class that is called Òhuman beingsÓ). The class of human beings has a set of
characteristics and
behaviours in common which are different from other
classes such as animal or
vehicle classes. When we want to define an
object in our program, we need to define its class first. An object is created
from a class. If there is no class, then no object can be created. If we take the example of
student class, each student has a set of variables (such as matric
number, name, age, address, etc) and methods or behaviours
(such as register course, withdraw course, etc). Each of the student
has his/her own set of variables and can call the methods independently. Any
call to methods will change itÕs variable. For
example, a repeated call to the register course method will increase the value of
the number of courses registered.
A class is a blueprint that defines the
variables (or attributes) and the methods common to all objects of a certain
kind. In the real world, we often
have many objects of the same kind.
For example, your car is just one of many cars in the world. In object-oriented context, we say that
your car object is an instance of the class of objects known as cars. Cars have some state (current gear,
current speed, four wheels) and behavior (change gears, change speed) in
common. However, each car's state is independent and can be different from that
of other cars. When building them, manufacturers take advantage of the fact
that cars share characteristics, manufacturing many cars from the same
blueprint. It would be very inefficient to produce a new blueprint for every
car manufactured. In
object-oriented software, it's also possible to have many objects of the same
kind that share characteristics: employee records, video clips, students record
and so on. Like car manufacturers, you can take advantage of the fact that
objects of the same kind are similar and you can create a blueprint for those
objects.
Figure 1.2: Objects created
from the class Student
Figure 1.3: Objects created from the class Car
1.2 DEFINING
CLASSES A
class is the template for an object just like data type int. But there is a
difference between class and primitive data type such as int or
double. That is when you define a class, you need to tell Java the characteristics of the
class you created but when you define an int data type, the compiler knows
what an integer is and you are not required to specify anything. Below is the structure of a class in Java:
This declaration is divided into three components: <class_name> This component is the class name that we declare. <attribute(s)> This component is the list of attributes for each object created from this class. In Java, the object attributes can be defined
as variables and it is called
as member variables or instance variables. <operation(s)> This component is the list of behavior
for all objects created from
this class. These behaviors
is defined as member methods. We
define a class by using the class
keyword followed by the class name. The class body is marked off by curly
braces just like a program block. The following is Java class which does
nothing.
The above class Student is
an empty class; it does nothing.
However, you can compile the class and create an object from it. To make
Student a useful class, it must have some attributes (that will represent its
state) and methods (that will represent its behaviour).
Assume the class Student will have
the following states (we just limit to EIGHT states only): á
Student's
Name á
Student's
matric number á
Student's
year birth á
Student's
age á
Fees
to be paid by the student á
Number
of courses registered by the student á
Name
of the subjects registered by the student á
Registration
status of the student The above states are
represented as attributes in a class. To declare ttributes
in a class use the following syntax: data_type attribute_name; You need to type the appropriate
date type followed by the name of the attribute asshown
below: Program
1.1: public class Student { private String
name;
private int matricNo;
private int yearBirth;
private int age;
private
double fees;
private int numberOfCoursesRegistered;
private String[
] subjectName;
private boolean registered; } Note: The keyword that is private written together with the
attribute declaration in the above program is an access modifier and itÕs not
compulsory. You will learn about access modifier in the next topic. The above class declares eight
attributes (1 String type attribute, 4 integer type attributes, 1 double type
attribute, 1 String type array and 1 boolean
data type).
1.3
CREATING AN
ABJECT FROM A DEFINED CLASS When you create a class you
are actually describing how objects of that class look and how they will
behave. You donÕt actually get anything from this class until you create an
object of that class with the keyword new. The following are syntax to create an object from
a class: Class_Name Object_Name = new Constructor_Name( ); The following example shows
how you can create an object from the Student class shown in Program 1.1 using
the above syntax: Program
1.2 (a): Line
1: class obj { Line
2: public static
void main (String[ ] args ){ Line
3:
Student John = new Student( ); // create the
object Line
4: } Line
5: } The
meaning for all the elements stated in Line 3 in the above program is given
below:
Take note that the Class_Name and the Constructor_Name are the same. Alternatively, you also can
use the following syntax in order to create an object from a class: Class_Name Object_name; Object_Name = new
Constructor_Name( ); The following example shows
how you can create an object from the Student class shown in Program 1.1 using
the above syntax: Program
1.2 (b): class obj
{ public static
void main (String[ ] args ){ Student John ; //reference type John = new Student(
); // create the object } } The state of the John object
after execution of the Program 1.2(a) or Program 1.2(b) is diagrammatically
shown below:
Figure 1.4: Object created from the class Student Can you create more than
one object of the same class in a program? Of course you can as long as your computer
memory can support it.
|
|
The effect of this new keyboard:
It is not compulsory for us to assign initial values
to all the attributes in the class. You could see that the attributes age and
fees are not given any initial value in the constructor of the Program 1.4. Also,
sometimes the initial also could be assigned during attribute declaration or in
other operational methods. For example, the initial value for the attribute registered was assign during its declaration.
Besides using constructors to initialize the
attributes, it also can be used to perform tasks related to creation like performing initial
calculations, etc

(You should understand Section
3.4 of Topic 3 before reading through this section. Good understanding about
method elaborated in Section 3.4 will help
you to understand this
section better)
Do you know that
merely declaring attributes and constructor in a class is not so complete?
To
make your class more useful, you must include "operations" in the
class. Operations in a class are represented by member methods. The method calculateAge()
found in Program 1.6 is an example of member method. Remember that member
method is one of the components that make up a class. What is the difference
between constructor and member method? The answer is given in the following
table.
Table 1.2: Differences between Constructor and Member Method
|
Constructor |
Member Method |
|
The name of the constructor method is same as the
name of the class |
The member method can be given any meaningful
name except the name of the class |
|
Constructor method cannot have any return value |
Constructor method may or may not return value |
|
Constructor method is used to initialize
attributes |
Member
method is used to perform some calculations such calculate age, get
maximum number, get random number, etc. |
There are three
types of member methods that could be written in a class namely: query method, update
method and task method. Query method is used
to access only the objectÕs state and this operation does not change the state
of a object. Example of this method are: getName(), getPay(), RetrieveID(),
checkPassword()
Update method is used
to update or change the value of attribute(s) of a object. This
update operation will change the state of the object. Example of this method are:
setName(), updateAge().
Finally, task methods is used to perform some specific task. This method may change
the state of the object. Example of this method are: calculateAge(), convertToCelcius().
Unlike constructor method which is called
during method creation, member method is called after an object has been
created. To give you some example on member methods, we are going to expand Program
1.6 by adding the following operations:
á
Calculate
fees - fees is calculated based on number of subjects registered
á
Capture
the subject names to be registered by the students
á
Display
the personal information of the student
Note: Of course
the list can be long but we just limit it to three operations only for the sake
of the discussion.
Each of the above
operation can be represented by different member methods. After taking
consideration the above operations, the new revised program with member methods
is shown below:
Program 1.8:
public class Student {
private String name;
private int matricNo;
private int yearOfBirth;
private int age;
private double
fees;
private int numberOfCoursesRegistered;
private String[
] subjectName;
private boolean
registered= false;
public Student (String NAME, int MATRIC, int B_YEAR) {
name= NAME;
yearOfBirth=B_YEAR;
matricNo= MATRIC;
numberOfCoursesRegistered=0;
subjectName= new String[3];
calculateAge();
}
private void calculateAge
(){
int currentYear=2008;
age= currentYear-yearOfBirth;
}// calculateAge
public void calculateFee
(){
if (registered==true)
fees=numberOfCoursesRegistered*350;
}// calculateFee
public void registerSubject (String subject1){
if (registered==false) {
subjectName[0]=subject1;
numberOfCoursesRegistered=1;
registered=true;
}
else
![]()
System.out.println(ÒYou already registeredÓ);
}// registerSubject
public void registerSubject (String subject1, String subject2){
if (registered==false) {
subjectName[0]=subject1;
subjectName[1]=subject2;
numberOfCoursesRegistered=2;
registered=true;
}
else
System.out.println(ÒYou already registeredÓ);
}// registerSubject
public void registerSubject
(String subject1, String subject2, String subject3){
if (registered==false) {
subjectName[0]=subject1;
subjectName[1]=subject2;
subjectName[3]=subject3;
numberOfCoursesRegistered=3;
registered=true;
}
else
System.out.println(ÒYou already registeredÓ);
}//
registerSubject
public void displayInfo ( ) {
if (registered==true){
System.out.println(ÒName: Ò + name);
System.out.println(ÒMatric: Ò + matricNo);
System.out.println(ÒYear of Birth: Ò + yearOfBirth);
System.out.println(Òage Ò +age);
System.out.println(ÒFees: Ò + fees);
System.out.println(ÒNo of courses
registered:
+numberOfCoursesRegistered);
System.out.println(ÒCourses registered are:Ó);
for (int count=0; count < numberOfCoursesRegistered; count++)
System.out.println(subjectName[count]);
} //if
else
System.out.println(ÒInformation cannot be displayed because you have not registeredÓ
);
} //displayInfo
}//class
Members methods also can be
overloaded and overloaded methods must have same method name but with different
signatures as you could see in the methods registerSubject() of the
Program 1.8 (refer to section 3.4 in topic 3 for explanation on method overloading).
1.5.1 Calling Member Methods
In Program 1.8, we have
included few member methods that represent few operations. How this method
could be called to perform their designated task? Before a member method could
be called, the object of the class must be created first. Then, the appropriate
method could be called using the following syntax:
<object_name>.member_method_name;
Remember that member methods are called after the
object has been created. Here is how you can call member method calculateAge()
available in the Student class of the
Program 1.8:
Program
1.9 (a):
class obj
{
public static
void main (String[ ] args ){
Student John = new Student(ÒJohn
SmithÓ, 2345, 1969);
John.registerSubject(ÒJava ProgrammingÓ);
![]()
John.calculateFee( );
}
}
Note that the object John has not invoked all
the member methods in the Student class. It just invoke two member methods in
the Student class, namely registerSubject() and calculateFee(). After
executing the Program 1.9(a), the object John will be in the following state:

Figure 1.7: The state of object John after execution
of Program 1.9(a)
Program 1.1 Ð Program 1.9 is
not interactive (that is the inputs are not key in by the user during the
program run-time). The Program 1.9(b)
below shows of how Program 1.9(a) has been amended to make it interactive:

The
following statements are wrong because the object is trying to call the member
method before its creation.
Program
1.10 (Contains Error):
class obj
{
public static
void main (String[] args ){
John.displayAge();
Student John = new Student(ÒJohn SmithÓ,
2345, 1969);
}
}
Now consider the following program (Program 1.11).
Do you think the program is correct?
Program
1.11:
class obj
{
public static
void main (String[ ] args ){
Student John = new Student(ÒJohn SmithÓ,
2345, 1969);
John.calculateFee( );
John.registerSubject(ÒJava
ProgrammingÓ);
}
}
The above program is not so
accurate because the method calculateFee() is called before the method registerSubject().
This does not make sense because student need to register the subject through
the method registerSubject() before they can call the method calculateFee()
because fee is calculated based on the number of subjects registered.
REMEMBER:
The sequence of methods calling by
an object are very important. Objects need to call the methods according
to the proper order.
For example, we cannot call method registerSubject()
if an object Student has not done the registerSemester.
To make a program more robust and tolerance for errors, it will be good idea to
include codes in the member methods just to detect whether the method has been
called prematurely. The inclusion of the statement Òif
(registered==true)Ó in the method calculateFee() in Program 5.8 is an example of this.
An
object cannot call method that is not available in its class. The following
statements in the Program 1.12 are wrong because the object John (which is an
object of the class Student) is trying to call the method registerSemester() which is
not exist in the class Student.
Program
1.12 (Contains Error):
class obj
{
public static
void main (String[] args ){
Student John = new Student(ÒJohn SmithÓ,
2345, 1969);
John.registerSemester( ); /*
Error: method registerSemester() does not exist
in the
class Student */
}
}
Like member method, we cannot
call a constructor that does not exist in class. For example, Line 3 in the
following program is an error because it is calling constructor method with one
argument. You may recall that there is no constructor with one parameter in the
class Student.
Program 5.15 (Contains Error):
|
Line
1 |
class obj1 { |
|
Line
2 |
public static void main (String[ ] args){ |
|
Line
3 |
Student John = new Student(ÒJohn SmithÓ); //ERROR |
|
Line
4 |
} |
|
Line
5 |
} |
![]()
á
A
class is a blueprint that defines
the variables (or attributes) and the methods common to all objects of a
certain kind.
á
Components
that make up a class are attributes, constructors and member methods
á
Constructors
used to initialize the attributes while member methods are used to perform
operations on the attributes while attributes represent the state of the object
á
There
are some differences between constructor and member method in the aspects of
the syntax and the nature of their tasks
á
Object is an instance of class.
á
Object is the most important thing in the object
oriented paradigm.
á
The keyword new is used to create
an object from a class