Module CIT 383-Course Guide
Module CIT 383-Course Guide
COURSE
GUIDE
CIT383
ii
CIT383 COURSE GUIDE
Abuja Office
No. 5 Dar es Salaam Street
Off Aminu Kano Crescent
Wuse II, Abuja
Nigeria
e-mail: [email protected]
URL: www.nou.edu.ng
Published By:
National Open University of Nigeria
ISBN: 978-058-694-6
iii
CIT383 COURSE GUIDE
CONTENTS PAGE
Introduction…………………………………………………………. 1
What You Will Learn in This Course………………………………. 2
Course Aims………………………………………………………… 2
Course Objectives…………………………………………………… 2
Working through This Course……………………………………..... 3
Course Materials…………………………………………………….. 3
Study Units………………………………………………………….. 3
Textbooks and References………………………………………….. 4
Assignment File……………………………………………………… 7
Presentation Schedule……………………………………………….. 7
Assessment…………………………………………………………… 7
Tutor-Marked Assignment (TMA)………………………………..… 8
Final Examination and Grading……………………………………… 8
Course Marking Scheme…………………………………………….. 9
Course Overview……………………………………………………. 9
How to Get the Most from This Course………………………………10
Facilitators/Tutors and Tutorials………………………………...........11
Summary…………………………………………………………..…..12
iv
Introduction
This course is divided into three modules. Module 1 introduces the basic
concept of object-oriented programming; discusses objects and classes
as the basis for OOD. The module also describes encapsulation,
abstraction, message passing and introduces composition, inheritance
and polymorphism.
In module 3, units 1 and 2 are discussed using Java while with C sharp
is used in units 3-5. This is done because Java does not support operator
overloading. Overloading is discussed in details. Some types of
overloading discussed are: method overloading, constructor overloading,
basic operators overloading. Others include overloading true and false,
logical operator overloading indexers.
This Course Guide gives you a brief overview of the course content,
course duration, and course materials.
Some of the concepts treated in the course require you to have some
basic background on some topics in computer science, especially
programming course. There is the need to have a fore-knowledge of
programming syntax. Therefore, you are advised to read through further
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
reading to enhance the knowledge you will acquire from this course
material.
Course Aims
Course Objectives
In order to ensure that this course achieves its aims, some general
objectives have been set though, every unit of this course has some set
objectives. By the end of every unit, you may need to check the
objectives to ensure that you have properly understood the topic treated.
After studying through the course, you should be able to:
ii
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Course Materials
These include:
1. Course Guide
2. Study Units
3. Recommended Texts
4. A file for your assignments and records to monitor your progress.
Study Units
iii
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Module 3 Overloading
iv
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
v
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Ken Arnold & James Gosling (1996). The Java Programming Language.
Addison Wesley.
vi
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Assignment File
These are of two types: the self-assessment exercises and the Tutor-
Marked Assignments. The self-assessment exercises will enable you
monitor your performance by yourself, while the Tutor-Marked
Assignment is a supervised assignment. The assignments take a certain
percentage of your total score in this course. The Tutor-Marked
Assignments will be assessed by your tutor within a specified period. At
the end of the course, the examination will test your understanding as
regards the concept and principle of the subject matter. This course
includes 15 Tutor-Marked Assignments and each must be done and
submitted accordingly. Your best scores however, will be recorded for
you. Be sure to send these assignments to your tutor before the deadline
to avoid loss of marks.
Presentation Schedule
Assessment
There are two aspects to the assessment of the course. First are the
Tutor- Marked Assignments; second, is a written examination.
At the end of the course, you will need to sit for a final three-hour
examination. This will also count for 70% of your total course mark.
vii
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Assignment questions for the units in this course are contained in the
Assignment File. You should be able to complete your assignments
from the information and materials contained in your set textbooks,
reading and study units. However, you may wish to use other references
to broaden your viewpoint and provide a deeper understanding of the
subject.
After completing the assignment, you should send it together with the
form to your tutor. Make sure that each assignment reaches your tutor
on or before the deadline given. If, however, you cannot complete your
work on time, contact your tutor before the assignment is done to
discuss the possibility of an extension.
The final examination for the course will carry 70% percentage of the
total marks available for this course. The examination will cover every
aspect of the course, so you are advised to revise all your corrected
assignments before the examination.
This course endows you with the status of a teacher and that of a learner.
This means that you teach yourself and that you learn, as your learning
capabilities would allow. It also means that you are in a better position
to determine and to ascertain the what, the how, and the when of your
learning. No teacher imposes any method of learning on you.
The course units are similarly designed with the introduction following
the table of contents, then a set of objectives and then the dialogue and
so on.
The objectives guide you as you go through the units to ascertain your
knowledge of the required terms and expressions.
viii
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
This table shows how the actual course marking is broken down.
Course Overview
Unit Title of Work Weeks Assessment
Activity (End of Unit)
Course Guide Week 1
Module 1 Basic Concepts of Object-Oriented Programming
1 Introduction to Object and Classes Week 1 Assignment 1
2 Message Passing and Encapsulation Week 2 Assignment 2
3 Inheritance Week 3 Assignment 3
4 Polymorphism and Modulation Week 4 Assignment 4
5 Composition and Abstraction Week 5 Assignment 5
Module 2 Object-Oriented Programming Properties Using any
Programming Language
1 Classes and Objects Week 6 Assignment 6
2 Constructors and Destructors Week 7 Assignment 7
3 Static Behaviours Week 8 Assignment 8
4 Inheritance and Composition Week 9 Assignment 9
5 Polymorphism Week 10 Assignment 10
Module 3 Overloading
1 Methods and Method Overloading Week 11 Assignment 11
2 Basic Operators Overloading Week 12 Assignment 12
3 Logical Operator Overloading Week 13 Assignment 13
4 Overloading True and False Week 14 Assignment 14
5 Conversion Operator Overloading and Week 15 Assignment 15
Indexers
Revision Week 16
Examination Week 17
Total 17 weeks
ix
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
In distance learning the study units replace the university lecturer. This
is one of the great advantages of distance learning; you can read and
work through specially designed study materials at your own pace, and
at a time and place that suit you best. Think of it as reading the lecture
instead of listening to a lecturer. In the same way that a lecturer might
set you some reading to do, the study units tell you when to read your
set books or other material. Just as a lecturer might give you an in-class
exercise, your study units provide exercises for you to do at appropriate
points.
Each of the study units follows a common format. The first item is an
introduction to the subject matter of the unit and how a particular unit is
integrated with the other units and the course as a whole. Next is a set
of learning objectives. These objectives enable you know what you
should be able to do by the time you have completed the unit. You
should use these objectives to guide your study. When you have
finished the units you must go back and check whether you have
achieved the objectives. If you make a habit of doing this you will
significantly improve your chances of passing the course.
Remember that your tutor’s job is to assist you. When you need help,
don’t hesitate to call and ask your tutor to provide it.
x
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
7. Review the objectives for each study unit to confirm that you
have achieved them. If you feel unsure about any of the
objectives, review the study material or consult your tutor.
8. When you are confident that you have achieved a unit’s
objectives, you can then start on the next unit. Proceed unit by
unit through the course and try to pace your study so that you
keep yourself on schedule.
9. When you have submitted an assignment to your tutor for
marking, do not wait for its return before starting on the next unit.
Keep to your schedule. When the assignment is returned, pay
particular attention to your tutor’s comments, both on the tutor-
marked assignment form and also written on the assignment.
Consult your tutor as soon as possible if you have any questions
or problems.
10. After completing the last unit, review the course and prepare
yourself for the final examination. Check that you have achieved
the unit objectives (listed at the beginning of each unit) and the
course objectives (listed in this Course Guide).
Your tutor will mark and comment on your assignments, keep a close
watch on your progress and on any difficulties you might encounter and
provide assistance to you during the course. You must mail or submit
your Tutor-Marked Assignments to your tutor well before the due date
(at least two working days are required). They will be marked by your
tutor and returned to you as soon as possible.
you do not understand any part of the study units or the assigned
readings,
you have difficulty with the self-tests or exercises,
you have a question or problem with an assignment, with your
tutor’s comments on an assignment or with the grading of an
assignment.
You should try your best to attend the tutorials. This is the only chance
to have face to face contact with your tutor and to ask questions which
xi
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
are answered instantly. You can raise any problem encountered in the
course of your study. To gain the maximum benefit from course
tutorials, prepare a question list before attending them. You will learn a
lot from participating in discussions actively.
Summary
Therefore, I wish you all the best you can get with the hope that you will
understand and find the course interesting.
xii
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
xiii
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Abuja Office
No. 5 Dar es Salaam Street
Off Aminu Kano Crescent
Wuse II, Abuja
Nigeria
e-mail: [email protected]
URL: www.nou.edu.ng
Published By:
National Open University of Nigeria
ISBN: 978-058-694-6
xiv
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS PAGE
xv
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Objects and Classes
3.1.1 Objects
3.1.1.1 Object Creation and Destruction
3.1.1.2 Accessing Objects
3.1.2 Classes
3.1.2.1 Accessing Class Members
3.1.2.2 Class Specification
3.1.2.3 Properties
3.1.2.4 Class Methods
3.1.2.4.1 Types of Methods
3.1.2.5 Inner Classes
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
16
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
2.0 OBJECTIVES
17
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
3.1.1 Objects
18
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Once a class has been specified, a data type exists with the same name.
You do not need to destroy or remove an object when it is no longer
needed. Java automatically flags unused objects and applies garbage
collection when appropriate. However you may occasionally need to use
finalise() method to insure that a non-Java resource such as a file handle
or a window font character is released first. The general form is:
void finalise ( )
{
/ / cleanup code goes here
Super.finalise ( ) / / parent too!
}
Object variables and methods are accessed using dot notation. Use
instance_name.variable or instance_name.method_name(args) to
reference instance objects declared with new. Use class_name.variable
or class_name.method_name(args) to reference static variables or
methods.
3.1.2 Classes
19
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Where modifier(s) are used to alter the behaviour of the class and,
usually, class members consist of named constants, variable
declarations, and/ or methods. That is, a member of a class can be either
a variable (to store data) or a method. Some of the modifiers that are
used are public, private, and static.
Note:
In the real world, one often finds out that many individual objects are all
of the same kind. There may be thousands of other bicycles in existence,
all of the same make and model. Each bicycle was built from the same
set of blueprints and therefore contains the same components. In object-
oriented terms, we say that your bicycle is an instance of the class of
objects known as bicycles. A class is the blueprint from which
individual objects are created. The following class is one possible
implementation of a bicycle:
20
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void printStates() {
System.out.println("cadence:"+cadence+" speed:"+speed+"
gear:"+gear);
}
}
The syntax of the Java programming language will look new to you, but
the design of this class is based on the previous discussion of bicycle
objects. The field’s cadence, speed, and gear represent the object's state,
and the methods (changeCadence, changeGear, speedUp etc.) define its
interaction with the outside world. You may have noticed that the
Bicycle class does not contain a main method. That's because it's not a
complete application; it's just the blueprint for bicycles that might be
used in an application. The responsibility of creating and using new
Bicycle objects belongs to some other class in your application. The
next example is a BicycleDemo class that creates two separate Bicycle
objects and invokes their methods:
class BicycleDemo {
public static void main(String[] args) {
21
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
The output of this test prints the ending pedal cadence, speed, and gear
for the two bicycles:
Once an object of a class is created, the object can access the members
of the class. The general syntax for an object to access a data member or
a method is:
referenceVariableName.memberName
The class members that the class object can access depend on where the
object is created.
A class specifies the properties (data) and methods (actions) that objects
can work with. It is a template or prototype for each of the many objects
made to the class design. The syntax for a class is:
22
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
3.1.2.3 Properties
23
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
24
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
The parameter list can contain from zero to many entries of datatype
varName pairs. Entries are separated by commas. Parameters are passed
by value, thus upholding the encapsulation principle by not allowing
unexpected changes or side effects. Object references (such as arrays)
can also be passed. The projects page has some simple problems based
on array passing. Some examples of method header parameter lists are:
3.1.2.4.1Types of Methods
Note: That there is no class keyword or return data type keyword. Also
the method name is the same as the class name. This is what marks the
fragment as a constructor method. If no constructor method is defined
for a class, a default constructor is automatically used to initialise all
fields to 0, false or unicode(0) as appropriate to the data type. The best
programming device is to declare the constructor with no parameters as
private and use it to initialise all properties. Then other constructors can
first call it using this() and then do their own specific property
validations/initialisation.
Accessor (or observer) methods read property (i.e. field variable) values
and are conventionally named getFoobar() or whatever the property is
called while Mutator (or transformer) methods set property values and
are often named setFoobar() etc. Mutators can be used to ensure that the
property's value is valid in both range and type.
25
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Class Factorial
{
Int factorial ( int n)
{
If ( n= =1 ) { return 1};
Return ( n * factorial (n-1 ) ) ;
}
}
Note: This short method is not very well written as negative and floating
calling parameters are illegal in factorials and will cause problems in
terminating the loop. Bad input should always be trapped.
Inner classes are classes nested inside another class. They have access to
the outer class fields and methods even if marked as private. Inner
classes are used primarily for data structures, helper classes, and event
handlers. A brief example of how an inner class can be used as a data
structure is:
26
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
4.0 CONCLUSION
5.0 SUMMARY
27
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
28
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 The Model
3.2 Influences on other Programming Models
3.3 Encapsulation
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
2.0 OBJECTIVES
29
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Messages are also commonly used in the same sense as a means of inter-
process communication; the other common technique being streams or
pipes, in which data are sent as a sequence of elementary data items
instead (the higher-level version of a virtual circuit). Examples of
Message passing styles are:
a. Actor model implementation
b. Amorphous computing
c. Antiobjects
d. Flow-based programming
e. SOAP (protocol)
3.3 Encapsulation
In OOD, objects combines data and operations on that data in a single
unit, the feature called encapsulation. The object is first identified, then
the relevant data and then the operations which are needed to
manipulate the objects.
30
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
4.0 CONCLUSION
31
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
5.0 SUMMARY
32
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
UNIT 3 INHERITANCE
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 What is Inheritance?
3.2 Building Inheritance Hierarchies
3.3 Inheriting Interface and Implementation
3.4 Hiding Fields
3.4.1 Abstract Classes and Methods
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
2.0 OBJECTIVES
define inheritance
differentiate between a subclass and a super class
outline the uses of a super class
differentiate between inheritance and overridden.
33
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
For instance, once the problem domain is partitioned into types, one will
likely want to model relationships in which one type is a more specific
or specialised version of another. For example you may have identified
in your problem domain two types, Cup and CoffeeCup, and you want
to be able to express in your solution that a CoffeeCup is a more specific
kind of Cup. In an object-oriented design, you model this kind of
relationship between types with inheritance.
34
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
class Cup {
}
class CoffeeCup extends Cup {
}
class CoffeeMug extends CoffeeCup {
}
This declaration of Cup has the same effect as the earlier one that
excluded the "extends Object" clause. If a class is declared with no
extends clause, it by default extends the Object class. (The only
exception to this rule is class Object itself, which has no superclass.)
The inheritance hierarchy of Figure 3.1 could also have shown the
Object class hovering above the Cup class, in its rightful place as the
35
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
36
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
When you override a method, you can make the access permission more
public, but you cannot make it less public. So far, you have only been
introduced to two access levels, public and private. There are, however,
two other access levels that sit in-between public and private, which
form the two ends of the access-level spectrum. In the case of the
addLiquid() method, because class Cup declares it with public access,
class CoffeeCup must declare it public also. If CoffeeCup attempted to
override addLiquid() with any other access level, class CoffeeCup
would not compile.
37
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
38
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Java permits you to declare a field in a subclass with the same name as a
field in a superclass so you can add fields to a class without worrying
about breaking compatibility with already existing subclasses. For
example, you may publish a library of classes that your customers can
use in their programmes. If your customers subclass the classes in your
library, you will likely have no idea what new fields they have declared
in their subclasses. In making enhancements to your library, you may
inadvertently add a field that has the same name as a field in one of your
customer's subclasses. If Java didn't permit field hiding, the next time
you released your library, your customer's program might not run
properly, because the like- named field in the subclass would clash with
the new field in the superclass from your library. Java's willingness to
tolerate hidden fields makes subclasses more accepting of changes in
their superclasses.
Java provides a way to declare a class as conceptual only, not one that
represents actual objects, but one that represents a category of types.
Such classes are called abstract classes. To mark a class as abstract in
Java, you merely declare it with the abstract keyword. The abstract
keyword indicates the class should not be instantiated. Neither the Java
compiler nor the Java Virtual Machine will allow an abstract class to be
instantiated. The syntax is straightforward:
// In Source Packet in file inherit/ex6/Liquid.java
abstract class Liquid {
void swirl(boolean clockwise) {
System.out.println("One Liquid object is swirling.");
}
static void gurgle() {
System.out.println("All Liquid objects are gurgling.");
}
}
39
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
The above code makes Liquid a place holder in the family tree, unable
to be an object in its own right.
Note that the Liquid class shown above still intends to implement a
default behaviour for swirling and gurgling. This is perfectly fine;
however, classes are often made abstract when it doesn't make sense to
implement all of the methods of the class's interface. The abstract
keyword can be used on methods as well as classes, to indicate that the
method is part of the interface of the class, but does not have any
implementation in that class. Any class with one or more abstract
methods is itself abstract and must be declared as such. In the Liquid
class, you may decide that there is no such thing as a default swirling
behaviour that all liquids share. If so, you can declare the swirl() method
abstract and forgo an implementation, as shown below:
Most often you will place abstract classes at the upper regions of your
inheritance hierarchy, and non- abstract classes at the bottom.
Nevertheless, Java does allow you to declare an abstract subclass of a
non- abstract superclass. For example, you can declare a method
inherited from a non-abstract superclass as abstract in the subclass,
thereby rendering the method abstract at that point in the inheritance
hierarchy. This design implies that the default implementation of the
method is not applicable to that section of the hierarchy. As long as you
40
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
implement the method again further down the hierarchy, this design
would yield an abstract class sandwiched in the inheritance hierarchy
between a non-abstract superclass and non- abstract subclasses.
4.0 CONCLUSION
5.0 SUMMARY
The generic class is known as the superclass or base class and the
specific classes as subclasses or derived classes. The concept of
inheritance greatly enhances the ability to reuse code as well as
making design a much simpler and cleaner process.
In Java terminology, a more general class in an inheritance
hierarchy is called a superclass. A more specific class is a
subclass.
When a class has only one direct super class, it is referred to as
single inheritance. In contrasts with a multiple inheritance, in
which a class can have multiple direct superclasses.
Overriding methods is a primary way a subclass specialises its
behaviour with respect to its superclass.
Well-designed classes most often refuse other classes direct
access to their non-constant fields, and this policy generally
extends to subclasses as well. If a super class has private fields,
those fields will be part of the object data in its subclasses, but
they will not be "inherited" by the subclass.
Java permits one to declare a field in a subclass with the same
name as a field in a superclass so that one can add fields to a class
without worrying about breaking compatibility with already
existing subclasses.
41
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
42
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
1.0 Objectives
3.0 Main Content
3.1 What is Polymorphism?
3.2 Types of Polymorphism
3.3 Modularity
3.3.1 Methods
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
Polymorphism is the capability of an action or method to do different
things based on the object that it is acting upon. This is the third basic
principle of object-oriented programming. Overloading and overriding
are two types of polymorphism.
2.0 OBJECTIVES
At the end of this unit, you should be able to:
describe polymorphism
state types of polymorphism
define modular programming
list the functions of modular programming.
43
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
In a class of hierarchy, several methods may have the same name and
the same formal parameter list. Moreover, a reference variable of a class
can refer to either an object of its own class or an object of its subclass.
Therefore, a reference variable can invoke, that is, execute, a method of
its own class or of its subclass(es). Binding means associating a method
definition with its invocation, that is, determining which method
definition gets executed. In early binding, a method’s definition is
associated with the method’s invocation at execution time, that is, when
the method is executed. Except for a few cases, java uses late binding
for all methods. Furthermore, the term polymorphism means assigning
multiple meanings to the same method name.
The reference variable name or nameRef can point to any object of the
class Person or the class PartTimeEmployee. Loosely speaking, one
could say that these reference variables have many forms, that is, they
are polymorphism reference variables. They can refer to either objects of
their own class or objects of the subclasses inherited from their class.
The following example further explains polymorphism.
44
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 4.1
45
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
3.3 Modularity
Methods in Java are like automobile parts’, they are building blocks.
Methods are used to divide complicated program into manageable
pieces. They are both predefined methods, methods that are already
written and provided by java, and user-defined methods, methods that
you create. Using methods has several advantages:
While working on one method, you can focus on just that part of
the program and construct it, debug it and perfect it.
Different people can work on different methods simultaneously.
If a method is needed in more than one place in a program, or in
different program, you can write it once and use it many times.
Using methods greatly enhance the programmes readability
because it reduces the complexity of the main method.
Methods are often called modules. They are like miniature
programmes; you can put them together to form a larger program.
The ability is less apparent with the predefined methods because
their programming code is not available to us. However, because
predefined methods are already written for us, this will be learnt
first, so that it could be used when needed. To use a predefined
method in your program (s), you need to know only how to use it.
46
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
3.3.1 Methods
A car can be seen as an object of a class vehicle. When you drive a car,
pressing its accelerator sends a message to the car to perform a task i.e.
make the car move faster. Similarly, messages are sent to an object of a
class. Each message is known as a method call and tells a method of the
object to perform its task. Methods are used to facilitate the design,
implementation, operation and maintenance of large programmes. A
method is invoked by a method call, and when the called method
completes its task, it either returns a result or simply the control to the
caller.
47
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
The methodname is any valid variable name. The method may or may
not have parameters depending on the method action. If a method has
parameters, when such method is to be called, the signature of the
arguments must be equal to the specified signature in the called method.
Note that signature refers to the number of arguments and the data type
of the arguments. Just like classes, methods have a method body that
begins and ends respectively with a left brace “{“and a right brace “}”.
A method may or may not return a value. A method that has a return
type of void does not return any value to its caller, thus, the second to
the last line is absent i.e. return value. It is important to Note that for
methods that do not have a return type of void, the last line before the
closing brace in the method should be the return value.
4.0 CONCLUSION
48
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Methods are often called modules. They are like miniature programmes;
you can put them together to form a larger program. Modular
programming involves the procedures of a common functionality which
are grouped together into separate modules. A program therefore no
longer consists of only one single part. It is now divided into several
smaller parts which interact through procedure calls and which form the
whole program.
5.0 SUMMARY
In this unit, the following have been discussed:
Several methods may have the same name and the same formal
parameter list in a class of hierarchy.
A reference variable can invoke, that is, execute, a method of its
own class or of its subclass(es). Binding means associating a
method definition with its invocation, that is, determining which
method definition gets executed.
Overloaded methods are methods with the same name signature
but either a different number of parameters or different types in
the parameter list.
Methods are often called modules. They are like miniature
programmes; you can put them together to form a larger program.
With modular programming procedures, common functionality is
grouped together into separate modules.
Although, most methods execute in response to method calls on
specific objects, this is not always the case. Sometimes a method
performs a task that does not depend on the contents of any
object. Such a method is called a static method.
49
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Composition
3.2 Abstraction
3.2.1 Abstract Classes
3.2.2 Interfaces
3.2.3 Abstract Data Types (ADT)
3.2.4 Importance of Data Structure Encapsulation
3.2.5 Generic Abstract Data Types
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
Volumes have been written regarding the application layers, web sites.
One of the fundamental activities of any software system design is
establishing relationships between classes. Two fundamental ways to
relate classes are inheritance and composition. Although the compiler
and Java virtual machine (JVM) will do a lot of work for you when you
use inheritance, you can also get at the functionality of inheritance when
you use composition. This unit discusses and compares these two
approaches to relating classes and will also provide guidelines on their
use.
2.0 OBJECTIVES
define composition
describe abstraction
define an abstract class
list abstract data types.
50
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
3.1 Composition
import java.util.GregorianCalendar;
51
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
over time, or keep track of the proportions of coffee and any additives
such as cream and sugar.
52
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
// No implementation yet
// (return 0 so it will compile)
return 0;
}
}
3.2 Abstraction
53
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
From the previous example, the superclass is more general than its
subclass(es). The superclass contains elements and properties common
to all of the subclasses. The previous example was of a concrete
superclass that instance objects can be created from. Often, the
superclass will be set up as an abstract class which does not allow
objects of its prototype to be created. In this case, only objects of the
subclass are used. To do this, the reserved word abstract is included in
the class definition.
54
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
3.2.2 Interfaces
Interfaces are similar to abstract classes but all methods are abstract and
all properties are static final. Interfaces can be inherited (i.e. you can
have a sub-interface). As with classes, the extend keyword is used for
inheritance. Java does not allow multiple inheritances for classes (i.e. a
subclass being the extension of more than one superclass). An interface
is used to tie elements of several classes together. Interfaces are also
used to separate design from coding as class method headers are
specified but not their bodies. This allows compilation and parameter
consistency testing prior to the coding phase. Interfaces are also used to
set up unit testing frameworks.
When you create a class that uses an interface, you reference the
interface with the phrase implements interface list. Interface list consists
one or more interfaces, as multiple interfaces are allowed. Any class that
implements an interface must include code for all methods in the
interface. This ensures commonality between interfaced objects.
55
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
1. It exports a type.
2. It exports a set of operations. This set is called interface.
3. Operations of the interface are the one and only access
mechanism to the type's data structure.
4. Axioms and preconditions define the application domain of the
type.
With the first property, it is possible to create more than one instance of
an ADT as exemplified with the employee example. You might also
remember the list example of chapter 2. In the first version, we have
implemented a list as a module and were only able to use one list at a
time. The second version introduces the “handle” as a reference to a “list
object”. From what we have learned now, the handle in conjunction with
the operations defined in the list module defines an ADT List:
56
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
“Let l=(d1, d2, d3, ..., dN) be a list. Then l.append(dM) results in l=(d1,
d2, d3, ..., dN, dM).”
“The first element of a list can only be deleted if the list is not empty.”
However, all of these properties are only valid due to our understanding
of and our discipline in using the list module. It is in our responsibility
to use instances of List according to these rules.
The principle of hiding the used data structure and to only provide a
well-defined interface is known as encapsulation. Why is it so important
to encapsulate the data structure?
ADTs are used to define a new type from which instances can be
created. As shown in the list example, sometimes these instances should
operate on other data types as well. For instance, one can think of lists of
apples, cars or even lists. The semantical definition of a list is always the
same. Only the type of the data elements change according to what type
the list should operate on. This additional information could be specified
57
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
List<Apple> listOfApples;
The angle brackets now enclose the data type for which a variant of the
generic ADT List should be created. listOfApples offers the same
interface as any other list, but operates on instances of type Apple.
4.0 CONCLUSION
Data: This part describes the structure of the data used in the
ADT in an informal way.
Operations: This part describes valid operations for this ADT,
hence, it describes its interface. We use the special operation
constructor to describe the actions which are to be performed
once an entity of this ADT is created and destructor to describe
the actions which are to be performed once an entity is destroyed.
For each operation, the provided arguments as well as
preconditions and post-conditions are given.
5.0 SUMMARY
58
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Create a class called Employee that has fields that stores employee’s
first name, last name, identification number, department name and
salary. Provide the necessary methods that provide meaningful output
when the class is used. Ensure data hiding. Test your class with an
executable class.
59
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Classes and Objects
3.2 Characteristics of a Class
3.3 Predefined Classes and User Defined Classes
3.4 Creating a Simple Class
3.5 Object Instantiation
3.6 Local Variables and Instance Variables
3.7 The Get and Set Methods
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
This unit discusses how classes are created in Java (one of the most
prominent and widely used Object-Oriented Programming Language).
The properties of classes and how to control access to members of a
class are also discussed. Object- oriented design (OOD) models software
in terms similar to those that people use to describe real world objects. It
takes advantage of class relationships, where objects of a certain class,
such as a class of vehicles have the same characteristics, for example,
cars, lorries and trailers have many characteristics in common.
60
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
The class is the abstract concept for an object that is created at design-
time by the programmer. The objects based upon the class are the
concrete instances of the class that occur at run-time.
2.0 OBJECTIVES
61
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Classes can relate with other classes e.g. in an object- oriented design of
a hospital, the “Patient” class need to relate with the “Nurse” class
which then relates with the “Doctor” class. All these classes cannot
exist in isolation. These relationships are called association. The
association property of a class makes software development an easy task
because a large project can be broken down into smaller classes which
then interact with one another to make the whole project.
With software reuse, each new class you create will have the ability to
become an asset that you and other programmers can use to speed and
enhance the quality of future software development efforts. Two major
aspects of Object- Oriented Programming that promotes software reuse
are Inheritance and Polymorphism. These two concepts will be
discussed later in this module.
A great strength of Java is its rich set of predefined classes that can be
reused rather than creating new classes. This is an aspect of software
reuse discussed earlier. Related classes are grouped into packages and
collectively referred to as the Java Class Library or the Java Application
Programming Interface (API). These predefined classes are the building
blocks for constructing new classes. Programmers use the import
declaration to identify the predefined classes used in a Java Program.
The syntax of the import statement is:
62
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
import packagename.classname;
Import packagename.class1name;
Import packagename.class2name;
……………………………………..
import packagename.classnname;
import packagename.*;
Note: In Computer terminology, “*” means all.
Some packages are implicitly imported into every Java Program. Thus
when the classes contained in such packages are to be used, there’s no
need to import such packages. An example of this is the package
Java.lang which contains the classes System and String. User defined
classes are the classes newly created by a programmer to assist in
achieving his desired task. Every Java program consist of at least one
user defined class declaration that is defined by the programmer. User
defined classes are also known as Programmer defined classes. The
class keyword introduces a user defined class declaration in Java and it
is followed immediately by the class name. A Java class name is a valid
identifier i.e. a series of characters consisting of letters digits,
underscores and dollar sign that does not begin with a digit neither does
it contain spaces.
The class body contains methods that specify the actions that the objects
of the class can exhibit. The class body begins and ends respectively
with a left brace “{“and a right brace “}”.
63
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 2.1.1
Program Input:
public class FirstProgram
{
public static void main(String[] args)
{
System.out.println("I love Java Programming");
}
}
// A program to display a line of text.
Program Output:
run:
Program Analysis:
64
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 2.1.2
Create a non executable class that has a method. This method prints a
line of text that reads “Object- Oriented Programming is fun”.
Program Input:
Program Analysis:
65
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 2.1.3
Program Input:
Program Output:
run:
Object- Oriented Programming is fun
BUILD SUCCESSFUL (total time: 3 seconds)
Program Analysis:
MessageClassTest is an executable class, the object of MessageClass
was created in this executable class and it is given the name msgclass.
The method displayMessage() in MessageClass is called msgclass, this
makes a line of text Object-Oriented Programming is fun to be
displayed in the output.
Local variables are variables that are declared in the body of a particular
method, such variables can be used only in that method. When that
method terminates, the values of its local variables are lost. Instance
variable must be initialised to their default value before they are used.
The syntax for declaring an instance variable within a method is:
Datatype variablename;
66
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Datatype is any valid data type and variablename is any valid variable
name. Instance variables are the attributes of a class. They are declared
inside the body of a class but outside the bodies of the class’s method
declarations. They are also called Fields. Each object of a class has its
own copy of attribute. Unlike local variables, instance variables are
initialised by default by a constructor. Constructors will be discussed in
details in Unit 2. The syntax for declaring an instance variable within a
class is:
private makes the variable accessible only within the class, public makes
it accessible within and outside the class, protected makes it accessible
within the class and other subclasses of the class. You will understand
how to use protected access modifier in unit 4 (inheritance).
Example 2.1.4
Create a non executable class that has a method that computes factorial.
Program Input:
Program Analysis:
67
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
The names of these methods need not begin with set or get but this
naming convention is highly recommended in Java. The next two
examples explain how the mutator and the accessor methods can be
used to manipulate the private instance variables of a class.
Example 2.1.5
Create a non executable class that has a private instance variable that
can hold the first name of a student. Your class should contain methods
to assign values to and retrieve values from the instance variable.
Program Input:
Program Analysis
68
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
are within the class. Method setFirstName stores a student’s first name.
It does not return any data when it completes its task, so its return type is
void. The method accepts one parameter name which is the first name
that will be passed to the method as an argument. In the body of this
method, the value name in the parameter is assigned to the instance
variable FirstName. i.e. this method sets the instance variable.
Example 2.1.6
Create an executable class that shows how the instance variables of the
SetGetClass2 can be manipulated by the methods of the class.
import java.util.Scanner;
class SetGetClass2Test
{
public static void main(String[] args)
{
Scanner myinput=new Scanner(System.in);
SetGetClass2 setgetclass2=new SetGetClass2();
String myname;
int myscore;
System.out.println("Unassigned first name is
"+setgetclass2.getFirstName());
System.out.println("Unassigned score is "+setgetclass2.getScore());
System.out.println("Enter your First name");
myname=myinput.nextLine();
System.out.println("Enter your Score");
myscore=myinput.nextInt();
setgetclass2.setFirstName(myname);
setgetclass2.setScore(myscore);
System.out.println(setgetclass2.getFirstName()+" scored
"+setgetclass2.getScore());
}
}
// A Program that accepts user’s input and uses the methods of
SetGetClass to manipulate the Input.
69
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Output:
run:
Unassigned first name is null
Unassigned score is 0
Enter your First name
Rebecca
Enter your Score
90
Rebecca scored 90
BUILD SUCCESSFUL (total time: 12 seconds)
Program Analysis:
The new thing you will discover in the output is that the default value of
an integer instance variable is 0. A careful examination of the lines of
codes will make you understand it better.
4.0 CONCLUSION
When you attempt to execute a class, Java looks for the class’s main
method to begin execution. Any class that contains the main method can
be used to execute an application. A method that belongs to another
class may not be called until an object of the class is created. Variables
declared in the body of a particular method are known as local variables
and can be used only in that method. Variables declared in the body of a
class are known as instance variables.
5.0 SUMMARY
70
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Review Exercise
Programming Exercise
71
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
72
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Objectives
4.0 Main Content
4.1 Constructors
4.1.1 Default Constructors
4.2 Creating Constructors
4.2.1 Creating a No Argument Constructor
3.2.2 Making a Constructor Behave Like a Default
Constructor
3.2.3 Creating an Argument Constructor
3.3 Constructor Overloading
3.4 Destructors (Tidying up)
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
In this unit, you will learn how the object of a class is been initialised.
Any time the object of a class is created, the object is implicitly
initialised, and this makes the object have a default value. Constructors
are used for such initialisations. Java provides a special kind of method,
called a constructor that executes each time an object of a class is
created. The constructor is used to initialise the state of an object. Apart
from the constructor provided by Java, Programmers can also create
their constructors, In such an instance, the mode of constructor creation
looks like that of a method but care must be taken not to mistake
methods for constructors. In this unit, you will learn how to create your
own constructor and you will be able to differentiate between a method
and a constructor.
73
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
2.0 OBJECTIVES
define a constructor
explain the concept of object initialisation
create a constructor
differentiate between constructors and methods
list multiple constructors in a class and use them as applicable.
3.1 Constructors
Constructors are special methods that are used to initialise a new object
of a class. Constructors have the same name as the class; the name of the
Student class's constructor is Student, the name of the Lecturer class's
constructor is Lecturer, etc. If you don’t define any constructor for your
class, the compiler will supply a default constructor to the class that
assigns a default value to the instance variable of a class’s object. This
was seen in unit 1, where the default value of a String instance variable
was seen to be null and that of integer was seen to be 0. During object
instantiation, the new keyword is used to invoke the constructor, in order
for it to assign default values to the object’s instance variable. If you
don’t want the instance variables of an object to take on default values,
you must create your own constructor.
The empty parenthesis after the Classname indicates a call to the class’s
constructor without argument which is often the default constructor. The
default value a constructor provides depends on the data type of an
object’s instance variables. Data types are divided into two categories;
primitive types and reference types. The primitive types are Boolean,
byte, char, short, int, long, float and double. All non primitive types are
reference types, so classes which specify the types of objects are
reference types. A String datatype is also a reference type. Primitive
type instance variables of char, short, int, long, float and double are
74
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
75
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 2.2.1
Create a class that has instance variables of String and Integers which
can respectively store a student’s first name and age. In the class, create
a constructor that assigns non default values to these variables.
Program Input:
Program Analysis
Two private instance variables of type String and int with names
firstname and age respectively were used. The non default no argument
constructor was created immediately after the instance variable
declaration. The instance variables are initialised in the constructor’s
76
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
body with values Grace and 25. With this, it is expected that when the
constructor is invoked, the default value of firstname and age will be
Grace and 25 respectively. Other methods were also created to assign
new values to and retrieve values from the instance variables (the set
and get methods). This allows the user to enter inputs for firstname and
age.
Example 2.2.2
Program Input:
}
public void setValues(String myname,int myage)
{
firstname=myname;
age=myage;
}
public String getFirstname()
{
return firstname;
}
public int getAge()
{
return age;
}
}
// A class that has a non default constructor that behaves like a default
constructor.
77
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis
Example 2.2.3
Program Input:
import java.util.Scanner;
public class StudentClass2Test
{
public static void main(String[] args)
{
Scanner myinput=new Scanner(System.in);
StudentClass2 stdclass2=new StudentClass2();
String name;
int age;
System.out.println("The initial students's name is:
"+stdclass2.getFirstname());
System.out.println("The initial students's age is:
"+stdclass2.getAge());
System.out.println("Enter your name");
name=myinput.nextLine();
System.out.println("Enter your age");
age=myinput.nextInt();
stdclass2.setValues(name,age);
System.out.println("The real name is: "+stdclass2.getFirstname());
System.out.println("The real age is: "+stdclass2.getAge());
}
}
// A program to test StudentClass2.
Program Output:
run:
The initial students's name is: null
The initial students's age is: 0
Enter your name
78
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Grace
Enter your age
25
The real name is: Grace
The real age is: 25
BUILD SUCCESSFUL (total time: 16 seconds)
Program Analysis:
The new thing that will be discovered in this program when compared to
StudentClassTest is in the output. Here, the initial values of the instance
variables firstname and age are respectively null and 0. This is because
of the non default constructor created in the StudentClass2 that behaves
like a default constructor.
Example 2.2.4
Create a class that has a String instance variable and an int instance
variable, in the class, create a constructor that has parameters that uses
these instance variables as its data.
Program Input:
79
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
return age;
}
}
// A class that shows how an argument constructor is created.
Program Analysis
The constructor of this class has a parameter that accepts a String value
and an int value as data, the constructor body sets the instance variable
of the class to the values in the parameter. This works like the set
method, so there may not be any need to include the set method. That is
why the set method is not included in the program. The get methods
retrieve the values of the instance variables. The next example creates an
object of Student3Class to see how the class’s constructor works.
Example 2.2.5
run:
The first students's name is: Grace
The first students's age is: 25
The second students's name is: Rebecca
The second students's age is: 38
BUILD SUCCESSFUL (total time: 6 seconds)
80
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis
This is the first time we will be creating more than one object of a class.
Two objects of StudentClass2 were instantiated and a constructor call
was invoked on them. The constructor has two arguments that accept a
first name and an age. Because each object has its own instance variable
in memory, that is why we are able to create two objects with different
instance variable. The instance variables for the first object are Grace
and 25 while the instance variables for the second object are Rebecca
and 38 as displayed in the output. These instance variables are set by the
constructor during the constructor call.
As you know, you can declare your own constructor to specify how
objects of a class should be initialised. In this section, we will explain
how multiple constructors can be used to initialise objects of a class in
different ways. These constructors are called overloaded constructors.
To overload constructors, simply provide multiple constructor
declarations with different signatures. The compiler differentiates
signatures by the number of parameters, the types of parameters and the
order of the parameter types in each signature. This will be further
explained in the next example.
Example 2.2.6
Create a time class that has 3 private instance variables hour, minute and
second. Your class should have overloaded constructors that can be used
to manipulate these instance variables.
Program Input:
81
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
minute=theminute;
}
public TimeClass(int thehour, int theminute, int thesecond)
{
hour=thehour;
minute=theminute;
second=thesecond;
}
public int getHour()
{
return hour;
}
public int getMinute()
{
return minute;
}
public int getSecond()
{
return second;
}
public String displayTime()
{
return
String.format("%02d:%02d:%02d",getHour(),getMinute(),getSecond());
}
}
// A time class that three time instance variables with constructors to
manipulate these variables differently.
Program Analysis
The time class has four constructors; the no argument constructor that
does not accept any time parameter, the one argument constructor that
accepts only the hour time parameter, the two argument constructors that
accept the hour and the minute time parameters and the three argument
constructor that accepts the hour, minute and the second time
parameters. All these constructors assign values to the time instance
variables in the constructor’s body. The getMethods retrieve the values
of the three time instance variables. The displayTime method returns a
String value that shows each of the time parameter in two digits
separated by “:”
Destructors are used to tidy up the computer’s memory. They are used to
delete unused objects from the memory. The local variables created
82
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
within the body of a method are automatically deleted once the control
is outside the method. This is not so for dynamically created objects.
Objects remain in memory until they are explicitly deleted. A destructor
is a special method typically used to perform cleanup after an object is
no longer needed by the program. C++ supports destructors, but JAVA
does not support destructors. JAVA supports another mechanism for
returning memory to the operating system when it is no longer needed
by an object. This mechanism is called garbage collection.
The garbage collector is a part of the runtime system that runs in a low-
priority thread reclaiming memory that is no longer needed by objects
used by the program. An object becomes eligible for garbage collection
in JAVA when there are no reference variables that reference the object.
The garbage collector makes use of a method finalise to perform its
housekeeping. The finalise method is called by the garbage collector to
perform termination housekeeping on object just before the garbage
collector reclaims the object’s memory. Method finalise does not take
parameters and has return type void. A problem with method finalise is
that the garbage collector is not guaranteed to execute at a specified
period. Infact, the garbage collector may never execute before a program
terminates. Thus, it is not certain that method finalise will be called all
the time. For this reason, the finalise method is rarely used.
4.0 CONCLUSION
7.0 SUMMARY
83
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Review Exercise
Programming Exercise
84
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
that initialises the three instance variables and assumes that the
values provided are correct. Provide a set and get method for
each instance variable. Provide a method displayDate that
displays the year, month and day separated by forward slashes (/).
Write a test application name DateClasssTest that demonstrates
class Date’s capabilities.
ii. Create a class called FreshStudentClass that includes four private
instance variables- firstname that can accept a student’s first
name, matricno that can accept a student’s matric number,
deptname that can accept a students’ department name and paid
that states whether a student have paid his bills or not. Instance
variable paid is a Boolean type that accepts true or false. Create
four constructors in this class that manipulates this instance
variable differently.
The FreshStudentClass should be tested to demonstrate the
constructors’ capabilities.
85
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Static Behaviours
3.2 Static Methods
3.2.1 Creating Static Methods
3.2.2 Static Predefined Methods
3.2.3 The Main Method
3.3 Static Fields
3.4 Static Imports
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
The methods, attributes and constructors that have been described so far
are all related to instantiated objects of classes. In each case, these
members have defined how the individual objects behave and how they
maintain and manipulate their own state. Sometimes you will want to
create behaviour that is not linked to any individual object; instead it
will be available to all instances and to objects of other classes. This is
where static members become useful.
In this unit, we will discuss the static behaviour of some class members
– methods and instance variables. You will see that at times, you don’t
need to create an object of a class before you invoke the class’s method,
the method can be directly called on the class and not the object. Such
methods are called static methods. You will also see that some
predefined classes have static methods which can be invoked directly on
the classes. It is common for some predefined classes to contain
convenient static methods to perform their tasks. We will also discuss
why method main is declared static. We discussed in unit one that every
object of a class has its own copy of all the class’s instance variable in
memory i.e. there’s a one-one relationship between the object of a class
and its instance variables. In this unit, you will learn that in certain
cases, only one copy of a particular variable should be shared by all
objects of a class. A static field called a class variable (not an instance
variable) is used in such a case. You will also learn in this unit, how the
import statement can be used to import static members of a predefined
class.
86
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
2.0 OBJECTIVES
Two members of a class can have the same static properties and they are
the methods of the class and the fields of the class. When the fields of a
class have a static behaviour, it is called a class variable. When these
static members of a class are used, the object of the class need not be
instantiated to make members carry out their work.
The way a static method is created is not too different from the way
normal methods are created. The only difference is the inclusion of the
static keyword. The syntax for creating a static method is shown below:
The keyword static usually comes before the return type in the method’s
declaration and the method may or may not accept parameters. Static
87
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
methods are usually called by specifying the name of the class in which
the method is declared, followed by a dot (.) and the method name as
shown below:
Classname.methodname(arguments);
Example 2.3.1
Program Input:
88
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis:
Example 2.3.2
Create an executable class that accepts two numbers from the user; the
computePermutation method should be called to compute the
permutation of two numbers.
Program Input:
import java.util.*;
public class PermutationClassTest
{
public static void main(String[] args)
{
Scanner myinput=new Scanner(System.in);
int num1,num2, result;
System.out.println("Enter the first number");
num1=myinput.nextInt();
System.out.println("Enter the second number");
num2=myinput.nextInt();
result= PermutationClass.computePermutation(num1,num2);
System.out.println(num1+" permutation "+num2+" is "+result);
}
}
// A program that uses the static computePermutation method of class
PermutationClass to compute the permutation of two numbers
Program Output:
run:
Enter the first number
5
Enter the second number
3
5 permutation 3 is 60
BUILD SUCCESSFUL (total time: 10 seconds)
89
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis:
An object of Scanner class was called to accept user’s input, the static
computePermutation method of the PermutationClass was called to
compute the permutation of the two entered numbers. This was done
without instantiating an object of PermutationClass.
There are some readymade static methods that can be used to achieve
special tasks. To use such methods, the import statement will be used to
import the class (if necessary) and the class’s name will then be called
directly on the object when the method is used. Some classes do not
need to be imported when their static methods are to be accessed. The
packages of such classes are implicitly imported by the compiler. A
common example of such packages is the Java.lang package. The
package has a class Math that has some static methods that enable you to
perform common mathematical calculations. Some of these static
methods are discussed below and our next programming example shows
how they work.
The first category of methods accepts only one argument. The second
category has two arguments. Care must be taken in the way the
90
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
arguments are placed when the pow method is used. If the arguments are
not placed in their correct position, a wrong answer may be returned.
From the table above, you can see that pow(2,5) and pow(5,2) returns
different values. The first argument is the base and the second one is the
index. This is further explained in the next example.
Example 2.3.3
Create an executable class that asks the user to input a number, the
number should be passed as argument to all the methods discussed and
the value of the computation should be displayed.
Program Input:
import java.util.*;
public class MathClassTest1
{
public static void main(String[] args)
{
Scanner myinput=new Scanner(System.in);
double num1;
System.out.println("Enter a number");
num1=myinput.nextDouble();
System.out.println("The absolute value of "+num1+" is
"+Math.abs(num1));
System.out.println("The cosine of "+num1+" in radians is
"+Math.cos(num1));
System.out.println("The sine of "+num1+" in radians is
"+Math.sin(num1));
System.out.println("The tangent of "+num1+" in radians is
"+Math.tan(num1));
System.out.println("The square root of "+num1+" is
"+Math.sqrt(num1));
System.out.println("The ceiling of "+num1+" is "+Math.ceil(num1));
System.out.println("The floor of "+num1+" is "+Math.floor(num1));
}
}
// A class that calls some static methods of class Math to perform some
mathematical computations.
Program Output:
Enter a number
1.5
The absolute value of 1.5 is 1.5
The cosine of 1.5 in radians is 0.0707372016677029
91
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis:
An object of the Scanner class accepts user input and each of the static
methods of class Math was called to make some computations. No
object of the Math class was created to do this but the class name and a
dot was prefixed to all these methods because they are static methods.
Every object has its own copy of the entire instance variables of the
class. In certain cases, only one of a particular variable should be
shared by all objects of a class. A static field is used in such an instance
and it is usually called a class variable. A static field or a class variable
has general information that is to be shared by all objects of the class.
The syntax for creating a static field is;
92
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
when no objects of the class exist, they are available as soon as the class
is loaded into memory at execution time. To access a public static field
when no objects of the class exist (and even when they do), prefix the
class name and a dot (.) to the static members. Private static members
can only be accessed within the class. When they are used, a public
static method must be provided and the method must be called by
qualifying its name with the class name and a dot (.).
There are two major static fields in the Math Class of Java.lang, these
fields are PI and E. These fields represent commonly used mathematical
constants, to use them, prefix their names with the class name which is
Math and a dot (.). Thus, we have Math.PI and Math.E. The constant
Math.PI is the ratio of a class’s circumference to its diameter and its
value is 3.14159265358979323846. The constant Math.E is the base
value for natural logarithms and its value is 2.7182818284590452354.
These fields are declared in the class Math with the modifier public,
final and static. Making them public allows other programmers to use
these fields in their own classes. They are declared final because their
values never change. Making them static allows them to be accessed
through the class name Math and a dot (.) separator.
Example 2.3.4
Program Input:
import java.util.*;
public class CircleTest
{
public static void main(String[] args)
{
Scanner myinput=new Scanner(System.in);
93
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
double radius;
System.out.println("Enter the radius of a circle");
radius=myinput.nextDouble();
System.out.println("The perimeter of a circle with radius "+radius+"
is "+(2*Math.PI*radius));
System.out.println("The area of a circle with radius "+radius+" is
"+(Math.PI*radius*radius));
}
}
// A program that uses the static field PI of the Math class to calculate
the perimeter and the area of a circle.
Program Output:
run:
Enter the radius of a circle
14
The perimeter of a circle with radius 14.0 is 87.96459430051421
The area of a circle with radius 14.0 is 615.7521601035994
BUILD SUCCESSFUL (total time: 4 seconds)
Program Analysis:
94
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 2.3.5
Import all static methods of class Maths explicitly and use some of these
methods to perform some computations without the class name and the
dot(.).
Program Input:
import java.util.*;
import static java.lang.Math.*;
class StaticImportClassTest
{
public static void main(String[] args)
{
Scanner myinput=new Scanner(System.in);
double num1,num2,num3;
System.out.println("Enter a number");
num1=myinput.nextDouble();
System.out.println("Enter another number");
num2=myinput.nextDouble();
System.out.println("Enter the last number");
num3=myinput.nextDouble();
System.out.println("The square root of "+num1+" is "+sqrt(num1));
System.out.println("The cosine of "+ num2+" is "+cos(num2));
System.out.println("The larger number between "+num2+" and
"+num3+" is "+max(num2,num3));
System.out.println(num2+" raise to the power of "+num3+" is
"+pow(num2,num3));
}
}
// A class that explicitly imports all the static methods of class Math.
Program Output:
run:
Enter a number
49
Enter another number
2
95
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis:
All the static methods in the Math class were imported explicitly and
when those methods were called, they were no prefixed with the class
name and a dot(.) as if they were created inside the class.
4.0 CONCLUSION
A class may contain static methods to perform common tasks that do not
require an object of the class. A static method is called by specifying the
name of the class in which the method is declared followed by a dot(.)
and the method name. A static variable represents class wide
information that is shared among all objects of the class. Static members
exist even when no objects of the class exist; they are available as soon
as the class is loaded into memory at execution time. To access a private
static member when no objects of the class exist, a public static method
must be provided. A static import declaration enables programmers to
refer to imported static members without the class name and a dot (.). A
single static import declaration imports one static member, and a static
import on demand imports all static members of a class.
7.0 SUMMARY
When methods directly called on the class and not the object,
such methods are called static methods. A static field called a
class variable (not an instance variable) is used in such a case.
The keyword static usually comes before the return type in the
method’s declaration and the method may or may not accept
parameters. Static methods are usually called by specifying the
name of the class in which the method is declared.
Some classes do not need to be imported when their static
methods are to be accessed. The packages of such classes are
implicitly imported by the compiler. A common example of such
packages is the Java.lang package.
96
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Review Exercise
a. x=Math.abs(-7.5);
b. x=Math.floor(-2.7);
c. x=Math.ceil(6.3);
d. x=Math.flooe(4.1);
e. x=Math.ceil(-2.5);
f. x=Math.pow(4,6);
g. x=Math.pow(7,2);
h. x=Math.ceil(-Math.abs(-5+Math.floor(-3.2)));
Programming Exercise
Write a program that works like a clock. Your class should be given the
name Time and it should have three private static fields hour, minute and
second that respectively represents the hour, the minute and the second
of a time. Whenever an object of time is created, it should be assumed
that 20 ticks have occurred, thus the second should increase by 20, when
it reaches 60, the minute should be increased by 20 and when the minute
reaches 60, the hour should increase by one. Test your time class and
ensure that it is working perfectly.
97
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
98
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
1.1 Objectives
3.0 Main Content
3.1 Inheritance
3.2 Superclasses and Subclasses
3.2.1 Protected Members
3.2.2 Data Hiding
3.3 Composition
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
99
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
2.0 OBJECTIVES
3.1 Inheritance
100
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
All public and protected superclass members retain their original access
modifiers when they become members of the subclass (i.e. the public
members of the superclass become the public members of the subclass
and protected members of the superclass become the protected members
of the subclass).
101
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 2.4.1
Note: Design the class in such a way that it will be used easily by
members offering the elective course.
Program Input:
102
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
{
double avg;
int approx;
char grade=0;
avg =getAverage();
approx=(int)(avg);
switch(approx/10)
{
case 10:
case 9:
case 8:
case 7:
grade='A';
break;
case 6:
grade='B';
break;
case 5:
grade='C';
break;
case 4:
grade='D';
break;
case 3:
case 2:
case 1:
grade='F';
break;
}
return grade;
}
public void getComment(char grade)
{
if (grade=='A'||grade=='B'||grade=='C')
System.out.println(firstname+" "+lastname+": "+"A bonafide
member");
else
System.out.println(firstname+" "+lastname+": "+"Not a bonafide
member");
}
103
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
}
// A superclass Member that has five protected members.
Program Analysis:
Example 2.4.2
From the example above, rewrite the Member class in a way that
promotes data hiding.
Program Input:
104
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
lastname=last;
mathscore=course1;
englishscore=course2;
sciencescore=course3;
}
public double getAverage()
{
return (mathscore+englishscore+sciencescore)/3;
}
public char getGrade()
{
double avg;
int approx;
char grade=0;
avg =getAverage();
approx=(int)(avg);
switch(approx/10)
{
case 10:
case 9:
case 8:
case 7:
grade='A';
break;
case 6:
grade='B';
break;
case 5:
grade='C';
break;
case 4:
grade='D';
break;
case 3:
case 2:
case 1:
grade='F';
break;
}
return grade;
}
public void getComment(char grade)
{
if (grade=='A'||grade=='B'||grade=='C')
105
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis:
The only new thing introduced is that all the fields that were declared as
protected before are now declared as private. This is to enhance data
hiding.
Example 2.4.3
Using the Member2 class as subclass, create a subclass that provides the
functions that can handle the necessary computations for students taking
the elective course.
Program Input:
Program Analysis:
The class has a new name that inherits from the modified Member class.
In the getAverage method, a call was made to the public method of the
superclass to return the average of scores in maths, English and science,
a quarter of the score in vocational studies is then added. This is because
this class no longer has a direct access to these three fields just because
they have been declared as private.
106
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
3.3 Composition
People often confuse composition for inheritance and vice versa. This is
because these two concepts allow class association. However, there is a
striking difference between inheritance and composition. Inheritance is
an is-a relationship whereas composition is an has-a relationship. In an
is-a relationship, an object of a subclass can also be treated as an object
of its superclass, e.g. a car (a subclass) is a vehicle (superclass). By
contrast, in an has-a relationship, an object has reference to other objects
e.g. a car has a steering wheel (i.e. a car object has a reference to a
steering wheel object). Composition allows a class to have references to
objects of other classes as members. It is also a form of software reuse.
Next examples explain composition. In these examples, three classes
will be created, the first class is the Date class and this class has three
private instance variables of date parameters- day, month and year.
The second class is the Student class and it has three private variables
pertaining to a student- firstname, lastname, and birthdate. Birthdate is
an object of the Date class, thus, a student object will have a reference to
members of the Date class because a student must have a birth date. The
third class tests the Student class to further explain the concept of
composition.
Example 2.4.4
Create a class Date that has all the three date parameters- day, month
and year. This class should have a method that displays date in a
meaningful format.
Program Input:
public class Date {
private int day;
private int month;
private int year;
public Date(int theday, int themonth, int theyear)
{
day=theday;
month=themonth;
year=theyear;
}
public String toString()
{
return
String.format("%02d%s%02d%s%d",day,"/",month,"/",year);
}
}
// A date class that displays date.
107
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis:
The three date parameters – day, month and year are declared private to
promote data hiding. A new method toString was called to display the
date in a meaningful format. This method is inherited from the implicit
direct superclass of Date called Object. Like it was said earlier all
classes have a direct or indirect superclass called Object. Method
toString is one of the most prominent methods of the Object class. The
next example shows how the object of a class can reference the variables
of a class. You will create a Student class, since every student is
expected to have a date of birth; you will reference the Date class in the
class.
Example 2.4.5
Create a class Student that has a field birthdate which is of the date type.
The class should have methods that can display the first name, last name
and the birth date of students.
Program Input:
Program Analysis:
The field birthdate is of the Date class, thus, it is a date datatype. The
constructor also takes as part of its argument a date data type
dateOfbirth since every student is expected to have a date of birth which
is a date data type. When the toString method is called on a date object,
108
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
the date is displayed in the format specified by the Date class in its
toString method.
Example 2.4.6
Program Input:
Program Output:
run:
Student's name: Grace Omotoso
Birth Date: 13/01/1990
BUILD SUCCESSFUL (total time: 1 second)
Program Analysis:
An object of Date class was first created and later passed to the
constructor during object instantiation. The getComment method of the
Student class was then called to display the first name, last name and
birth date of students.
4.0 CONCLUSION
109
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
5.0 SUMMARY
110
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Review Exercise
Programming Exercise
111
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
UNIT 5 POLYMORPHISM
CONTENTS
1.0 Introduction
2.0 Objectives
4.0 Main Content
4.1 Polymorphic Behaviours and Examples
4.2 Abstract Classes and Concrete Classes
4.3 Abstract Methods
4.4 Downcasting and Dynamic Binding
4.5 Final Methods and Classes
3.6 Interfaces
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
2.0 OBJECTIVES
112
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
113
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Not all classes can be used for object instantiations, most times, such
classes acts as a superclass and their main work is to make other classes
inherit their methods and to share a common design. Such classes are
called abstract classes. While abstract classes cannot be used for object
instantiation, concrete classes are classes that can be used for object
instantiation. The classes discussed so far in all our earlier examples are
concrete classes. Concrete classes provide implementations of every
method they declare whereas abstract classes contain at least one
method that does not have implementation.
114
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Case Study:
Example 2.5.1
Program Input:
115
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis:
The class is declared as abstract in the first line, this tells that it has at
least one method that has no implementation. The class contains three
private instance variables firstname, lastname and employee_id, since an
employee is expected to have a first name, a last name and an identity
number. The constructor body sets all these three instance variables. The
toString method is inherited from the implicit direct superclass Object
and it returns a string value that displays the first name, last name and
employee id of all employees. Method earnings is declared abstract
since it does not have implementation code, this is because different
categories of employee have earn different amounts. When subclasses of
employee extend the class, they must all provide the implementation
code for the method earning because this is part of the contract they will
sign with the abstract superclass before inheriting it.
Example 2.5.2
Create a class for the categories of employees that are paid hourly.
Program Input:
public class HourlyEmployee extends Employee{
double hours;
double rate;
public HourlyEmployee(String first, String last, String id, double
thehours, double therate)
{
super(first,last,id);
hours=thehours;
rate=therate;
}
public double earnings()
{
if(hours<=40)
return hours*rate;
else
return (40*rate)+((hours-40)*1.5*rate);
}
public String toString()
{
return String.format("\nHourly employee: %s \n%s%.2f\n%s%.2f",
super.toString(),"Hours worked: ",hours,
"Wages per hour: ",rate);
}
}
// A class for the hourly paid employees.
116
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis:
The class has two private variables hours and rate, since an hourly-
employee is paid based on the hours worked and the rate of wages per
hour. The constructor has five arguments, three of the arguments are set
by calling the superclass constructor and the remaining two are set
newly. Method earning returns the amount an hourly paid employee will
earn, overtime is also considered. The overtime is one-half the wages
per hour for each overtime hour. The method toString has a call to the
superclass, this displays the first name, last name and employee id, and
other parameters are also included to make the displayed result
complete.
Example 2.5.3:
Program Input:
Program Analysis:
117
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 2.5.4
Program Input:
Program Analysis:
The class has two private variables grossales and commissionrate, since
a commission-employee is paid based on the gross sales and the
commission rate. The constructor has five arguments, three of the
arguments are set by calling the superclass constructor and the
remaining two are set newly. Method earning returns the amount a
commission-employee will earn. The method toString has a call to the
superclass, this displays the first name, last name and employee id, and
other parameters are also included to make the displayed result
complete.
118
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
An object of a subclass is an object of its superclass just like all cars are
vehicles. An object of a superclass may not be an object of a subclass
just like all vehicles are not cars. Downcasting allows an object of a
superclass to behave like an object of a class, thus the methods of a
subclass can be called through a superclass reference. Dynamic binding
is the process through which the type (class) of an object is determined
at execution time rather than at compilation time. It is also called late
binding. Next examples explain the concept of downcasting and
dynamic binding.
Example 2.5.5
For the current pay period, the company has decided to reward the
salaried-commission employees by adding 5% to their base salaries. The
company wants you to implement this without altering the classes you
have already because it’s going to be a temporal process.
Clue: Use an executable class
Program Input:
119
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
new
BasePlusCommissionEmployee("Rebecca","Olufunke","07/001",5000,0.
04,300);
System.out.println("Employees processed Polymorphically");
Employee employees[]=new Employee[4];
employees[0]=hourlyemployee;
employees[1]=salaryemployee;
employees[2]=commissionemployee;
employees[3]=basepluscommissionemployee;
for(Employee currentemp: employees)
{
System.out.println(currentemp);
if (currentemp instanceof BasePlusCommissionEmployee)
{
BasePlusCommissionEmployee
emp=(BasePlusCommissionEmployee)currentemp;
emp.setSalary(1.05*emp.getSalary());
System.out.printf("new base salary with 5%% increase is:
#%,.2f\n",
emp.getSalary());
}
System.out.printf("earned #%,.2f\n",currentemp.earnings());
}
// An executable class that processes the objects of Employee subclasses
polymorphically.
Program Output:
run:
Employees processed Polymorphically
Hourly employee: Grace Omotoso
employee_id: 08/021
Hours worked: 16.75
Wages per hour: 40.00
earned #670.00
120
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis:
3.6 Interfaces
121
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
All objects of a class that implement multiple have the is-a relationship
with each implemented interface type. Next examples explain how an
interface can be used to make objects of unrelated classes to be
processed polymorphically.
Case Study:
Suppose that the company involved in our first case study wishes to
perform several accounting operations in a single amountPayable
application- in addition to calculating the earning paid to each employee,
the company must also calculate the payment due on each of several
invoices.
Example 2.5.6
122
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Input:
Program Analysis:
Example 2.5.7
Create a class Invoice that implements the Payment interface. This class
should show the product number and description, it should also show the
product quantity and the price of product. Method getPaymentAmount
should be implemented in this class to calculate the amount on the
invoice.
Program Input
123
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
}
}
// A class that implements the Payment Interface.
Program Analysis:
The first line of the program has the implement keyword. This shows
that it is making use of an interface called Payment. The
getPaymentAmount of this class is implemented because the class is not
declared as abstract, it is implicitly signing an agreement that it will
provide implementations for all the methods of the interface.
Example 2.5.8
Create a class that uses the interface Payment that can be used as a
superclass for any of the categories of employees discussed earlier.
Program Input:
Program Analysis:
124
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 2.5.9
Create a subclass for this new Employee2 superclass for the salaried-
employee category. This method should implement the
getPaymentAmount of the Payment interface.
Program Input:
Program Analysis:
The class is a concrete class. Even though the implement keyword was
not used in the first line, since it is a subclass of the Employee2 class
that implements the Payment interface, the class indirectly implements
the interface. It must provide implementations for the
getPaymentAmount method used in the interface since it is not declared
as abstract.
Example 2.5.10
125
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Input:
Program Output:
run:
Employees and invoices processed polymorphically
Invoice
Product id: 0101 (PS2)
Quantity: 5
Price per item: #500.00
Payment due: 2500.00
Invoice
Product id: 0201 (Optical)
Quantity: 7
Price per item: #700.00
Payment due: 4900.00
126
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis:
4.0 CONCLUSION
The is-a relationship applies only between a subclass and its superclass,
not vice-versa. However, downcasting allows a superclass object behave
like its subclass object. A method that is declared final in a superclass
cannot be overridden in a subclass.
127
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
interface declaration. A class that does not implement all the interface’s
methods is an abstract class and must be declared abstract.
5.0 SUMMARY
Review Exercise
128
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Programming Exercise
Shape
TwoDimensionalShap ThreeDimensionalSha
e pe
129
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
MODULE 3 OVERLOADING
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Methods
3.2 Creating and Using Methods
3.2.1 Argument Promotion and Casting
3.2.2 Random Number Generation
3.3 Method Overloading
3.4 Recursive Methods
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
Many of the classes you will use or create while developing applications
will have more than one method of the same name. This technique is
called method overloading and it is used to implement methods that
perform similar tasks for arguments of different types or for different
numbers of arguments. For some problems, it is useful to have a method
130
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
call itself; such a method is called a recursive method. You will learn the
concepts of recursion in this unit.
2.0 OBJECTIVES
3.1 Methods
Methods are one of the modules that exist in Java. The three kinds of
modules that exist in Java are methods, classes and packages. Methods
(called functions or procedures in other languages) allow programmers
to modularise a program by separating its tasks into self-contained units.
The statements in the method bodies are written only once, are reused
from perhaps several locations in a program and are hidden from other
methods. The following are the motivations for modularising a program
into methods:
131
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
The accesslevel describes how other methods in the class will be able to
access this method. The access level can either be public or private. A
private accesslevel makes the method inaccessible by others methods of
the class. A public access level makes the method accessible by other
methods of the class. Returntype describes the data type the method will
return to its caller. Return type can be any valid data type. A method that
has a return type of int returns an integer to its caller, while a method
that has a return type of String value returns a String value to its caller.
Sometimes a method may not return any value to its caller. Such
methods have a return type of void.
132
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
respectively with a left brace “{“and a right brace “}”. A method may or
may not return a value. A method that has a return type of void does not
return any value to its caller, thus, the second to the last line is absent i.e.
return value.
Note: For methods that do not have a return type of void, the last line
before the closing brace in the method should be the return value. All
programming examples in this Course book are compiled using the Java
Netbeans.
Example 3.1.1
Create an executable class that accepts two numbers from users, the
class should have a method that finds the difference of the two numbers;
the method should be called to display the difference of the two
numbers.
Program Input:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
double num1,num2;
Scanner myinput=new Scanner(System.in);
System.out.println ("Enter the first number");
num1=myinput.nextDouble();
System.out.println("Enter the second number");
num2=myinput.nextDouble();
System.out.println("The difference between "+num1+" and
"+num2+" is "+getDifference(num1,num2));
System.out.println("The difference between "+num2+" and
"+num1+" is "+getDifference(num2,num1));
}
public static double getDifference(double number1,double number2)
{
return number1-number2;
}
}
// A program that has a method that computes the difference of two
numbers.
133
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Output:
run:
Enter the first number
5
Enter the second number
3
The difference between 5.0 and 3.0 is 2.0
Program Analysis:
The program uses an executable class and the java.util package was
used to import the scanner class. An object of Scanner myinput was
created to accept inputs from users. The input expected from users are of
double types but in our output we entered integer values and no error
was returned, this is because the compiler was able to implicitly convert
the integer values to double values, you can see in the output that 5 and
3 entered by the user have been respectively changed to 5.0 and 3.0 by
the compiler. This process is called argument promotion and it will be
discussed in the next section. The method getDifference was declared as
static because it was used in the static main method. The method has
two parameters number1 and number2 both are of the double data type.
When the method was called in the main method, two arguments num1
and num2 were passed into the method. It should be noted that the
number of parameters and their datatypes in the method is equivalent to
the number of arguments and datatypes when the method was called.
Supplying any data other than the one specified in the method
parameters results to compilation error.
134
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
method arguments num1 and num2 and replacing them with the
parameters number1 and number2 and subtracting num2 from num1.
Since the method returns a value, this value is passed back to the output
segment of the main method. The next example illustrates how
information can be passed between methods.
Example 3.1.2
Program Input:
import java.util.Scanner;
public class Main {
Program Output:
run:
Enter the first number
9
Enter the second number
135
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
6
Enter the third number
4
The difference between 9.0 and the difference of 6.0 and 4.0 is 7.0
BUILD SUCCESSFUL (total time: 22 seconds)
Program Analysis:
The program is not far different from the one in example one, only that
the getDifference methods were embedded into each other in the output
segment of the main method. The outermost method is first executed,
this accepts 6 and 4 and returns 2 to the outermost method, the
outermost method uses the returned value as its second arguments. The
argument for the method is now 9 and 2 which then returns 7 as its
result.
136
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 3.1.3
Develop a non executable class that can be used for converting numbers
from one base to another. Modularise your program as much as possible
with methods so that the problem will be easier to solve.
Program Input:
else
num=giveDecValue(val);
result+=num*(int)Math.pow(base, (number.length()-1-i));
}
return result;
}
public boolean isNumber(char value)
{
if(value=='0'||value=='1'||value=='2'||value=='3'||value=='4'||value=
='5'
||value=='6'||value=='7'||value=='8'||value=='9')
return true;
else
return false;
}
public int giveDecValue(char number)
{
int hold=0;
switch(number)
{
137
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
case 'A':
hold=10;
break;
case 'B':
hold=11;
break;
case 'C':
hold=12;
break;
case 'D':
hold=13;
case 'E':
hold=14;
break;
case 'F':
hold=15;
break;
}
return hold;
}
public char giveHexaValues(int number)
{
char hold=' ';
switch(number)
{
case 10:
hold='A';
break;
case 11:
hold='B';
break;
case 12:
hold='C';
break;
case 13:
hold='D';
break;
case 14:
hold='E';
break;
case 15:
hold='F';
break;
}
return hold;
}
138
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Analysis:
Example 3.1.4
Test your number conversion class by accepting three inputs from users,
the first input is the number to convert, the second input is the base of
the number and the third input is the base you want to convert the
number to.
Program Input:
import java.util.Scanner;
public class NumberConversionTest {
public static void main(String[] args) {
139
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Input:
run:
Enter the number you want to convert
110011
Enter the initial base of the number
2
Enter the base you want to convert the number to
16
110011 in base 2 to 16 is 33
BUILD SUCCESSFUL (total time: 15 seconds)
run:
Enter the number you want to convert
A4B5
Enter the initial base of the number
16
Enter the base you want to convert the number to
10
A4B5 in base 16 to 10 is 42165
BUILD SUCCESSFUL (total time: 40 seconds)
140
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
141
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 3.1.5
Program Input:
import java.util.Scanner;
public class OverloadedMethods {
public static int minimum(int number1, int number2, int number3)
{
int min=number1;
if(number2<=min)
min=number2;
if(number3<=min)
min=number3;
return min;
}
public static double minimum(double number1, double number2,
double number3)
{
double min=number1;
if(number2<=min)
min=number2;
142
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
if(number3<=min)
min=number3;
return min;
}
public static double minimum(double number1, double number2, int
number3)
{
double min=number1;
if(number2<=min)
min=number2;
if(number3<=min)
min=number3;
return min;
}
public static void main(String[] args) {
Scanner myinput=new Scanner(System.in);
int intnum1=3,intnum2=7, intnum3=6;
double doublenum1=5.0, doublenum2=-2.3, doublenum3=-7;
System.out.println("The minimum of
"+intnum1+","+intnum2+","+intnum3+" is "+
minimum(intnum1,intnum2,intnum3));
System.out.println("The minimum of
"+doublenum1+","+doublenum2+","+doublenum3+" is "+
minimum(doublenum1,doublenum2,doublenum3));
System.out.println("The minimum of
"+doublenum1+","+doublenum2+","+intnum3+" is "+
minimum(doublenum1,doublenum2,intnum3));
}
}
// A program that has overloaded methods.
Program Output:
run:
The minimum of 3,7,6 is 3
The minimum of 5.0,-2.3,-7.0 is -7.0
The minimum of 5.0,-2.3,6 is -2.3
BUILD SUCCESSFUL (total time: 2 seconds)
Program Analysis:
There are three static methods in the program; these methods are
declared static because they are used inside the static main method. The
methods have the same and different signatures, when the methods are
called; the compiler is able to call the right method by comparing the
143
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Example 3.1.6
Program Input:
144
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Program Output:
run:
1! 1
2! 2
3! 6
4! 24
5! 120
6! 720
7! 5040
8! 40320
9! 362880
10! 3628800
Program Analysis:
The factorial method first solves the base case by specifying that
factorial of one or any number less than one should be zero, the complex
case is then solved by dividing the problem into two pieces which later
divides itself until the base case is reached. The next example we will
look at uses recursion to generate Fibonacci series.
4.0 CONCLUSION
Experience has shown that the best way to develop and maintain a large
program is to construct it from several small, simple pieces or modules.
This technique is called divide and conquer. Methods allow
programmers to modularise a program by separating its tasks into self-
contained units. The statements in a method are written only once and
hidden from other methods. Using existing methods as building blocks
to create new programmes is a form of software reusability that prevents
programmers from repeating codes within a program. When a method is
called, the program makes a copy of the method’s argument values and
assigns them to the method’s corresponding parameters, which are
created and initialised when the method is called. When program control
returns to the point in the program where the method was called, the
method parameters are removed from memory. A method can return at
most one value, but the returned value can be a reference to an object
that contains many values.
145
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
5.0 SUMMARY
Methods are one of the modules that exist in Java and the three
kinds of modules that exist in Java are methods, classes and
packages.
Methods (called functions or procedures in other languages)
allow programmers to modularise a program by separating its
tasks into self-contained units.
A method is invoked (i.e., made to perform its designated task) by
a method call. The method call specifies the name of the method
and may provide information (as arguments) that the called
method requires to perform its task.
Argument promotion is the process of converting an argument’s
value to the type that the method expects to receive in its
corresponding parameter.
Method overloading is commonly used to create methods with
the same name that perform the same or similar tasks, but on
different types or different numbers of arguments.
A recursive method is a method that calls itself which can be
called either directly or indirectly through another method.
146
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Review Exercise
Programming Exercise
147
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
148
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Objectives
5.0 Main Content
5.1 Basic Operator Overloading
5.2 Binary Operator Overloading
5.2.1 Creating the Addition (+) Operator
5.2.2 Creating the Subtraction (-) Operator
5.2.3 Creating the Multiplication (*) Operator
5.3 Unary Operator Overloading
5.3.1 Creating the Increment and Decrement Operator
5.3.2 Creating the Negation Operator
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
2.0 OBJECTIVES
149
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Java does not support operator overloading but an exception was made
for String by using the “+” symbol to concatenate string literals.
Although, this is out of the control of developers as it is a built- in
feature of Java. Developers have no control over operator overloading in
Java. Java does not support operator overloading because the designers
of Java wanted to keep Java codes simple and found that operator
overloading made code more complex and difficult to read. There are
other methods available to achieve the same functionality as operator
overloading, you could create methods in a class named plus (), minus
(), multiply (), etc... The designers of Java must have decided that
operator overloading in Java was more of a problem than it was worth.
X = 5 + 6;
However, there are times when a plus sign could represent something
else. For example, in the following code:
You would expect that Name would contain Joe Smith. The plus sign
here has been overloaded to perform string concatenation which is
commonly used in Java but it is a built- in feature of Java that cannot be
controlled by programmers.
150
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
The following codes create a vector class that can be used to manipulate
values that have two coordinates, e.g. 2x+6y, through operator
overloading, we can perform the basic mathematical operations on
members of the vector class.
public int X
{
get { return _x; }
set { _x = value; }
}
public int Y
{
get { return _y; }
set { _y = value; }
}
}
151
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
The syntax for binary operators can now be used to create a new
addition operator for the Vector class. This operator will simply add the
X and Y elements of two vectors together and return a new vector
containing the result. Add the following to the Vector class to provide
this functionality. Note that a new vector is created rather than adjusting
one of the operands. This is because the operands are reference-types
and the original values should not be updated in this case.
We can now test the vector's new operator by modifying the program's
main method. The following program instantiates two vector objects,
adds them together and outputs the values of the resultant vector's X and
Y properties.
Vector v3 = v1 + v2;
Console.WriteLine("({0},{1})", v3.X, v3.Y); // Outputs "(4,19)"
}
152
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
subtraction, this is not the case so it important to remember that the first
operand in the declaration represents the value to the left of the operator
and the second operand represents the value to the right. If these are
used incorrectly, the resultant value will be incorrect. Using this
knowledge we can add a subtraction operator to the Vector class:
Vector v3 = v1 - v2;
The last binary operator that will be added to the Vector class is
multiplication. This operator will be used to scale the vector by
multiplying the X and Y properties by the same integer value. This
demonstrates the use of operands of a different type to the class they are
defined within.
Vector v2 = v1 * 3;
In the operator code for the multiplication operator, the Vector is the
first operand and the integer the second. This means that the order used
153
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
in the multiplication statement must have the vector at the left of the
operator and the integer value to the right. Changing the order of the
operands in the Main method will cause a compiler error.
Vector v2 = 3 * v1;
Unary operators are those that require a single operand. These include
the simple increment (++) and decrement (--) operators. To declare a
unary operator, the following syntax is used:
This syntax is almost identical to that used for binary operators. The
difference is that only one operand is declared. The operand type must
be the same as the class in which the operator is declared.
Using the syntax defined above, we can now add the increment and
decrement operators to the Vector class. Note that there is only a single
definition for each. There is no way to differentiate between prefix and
postfix versions of the operator so both provide the same underlying
functionality. To declare the two operators, add the following code to
the Vector class. Each increments or decrements both affect X and Y
properties for Vector objects.
154
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
v1++;
Console.WriteLine("({0},{1})", v1.X, v1.Y); // Outputs "(5,12)"
v1--;
Console.WriteLine("({0},{1})", v1.X, v1.Y); // Outputs "(4,11)"
}
155
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
4.0 CONCLUSION
In this unit, you learnt that it is possible to change the way basic
operators like +, - , *, / etc behave in order to suit the programmers
work. Java does not support this but methods can be used to make Java
behave like that. Java was designed not to support operator overloading
because it makes Java codes complex but since Java was designed to
make programming easier, the feature was embedded into Java. Some
Object- oriented languages like C#/ C++ support the basic operator
overloading it.
8.0 SUMMARY
156
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
www.blackwasp.co.uk/CSharpObjectOriented.aspx
157
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 The Logical Operators
3.2 Overloading the Binary Boolean Logical Operators
3.2.1 Creating the Boolean AND Operator (&)
3.2.2 Creating the Boolean OR (|) and XOR (^)
Operators
3.3 Overloading the Unary Boolean Logical Operator
3.3.1 Creating the Boolean NOT Operator (!)
3.3.2 Enabling the Short-Circuit Operators
3.3.3 Adding the Short-Circuit Operator Pre-Requisites
to the Vector Class
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 Reference/Further Reading
1.0 INTRODUCTION
2.0 OBJECTIVES
158
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
There are four logical operators that can be directly overloaded for a
class. These are the NOT operator (!), the AND operator (&), the OR
operator (|) and the exclusive OR or XOR operator (^). The short-circuit
operators (&& and ||) cannot be overloaded directly. However, if the
class meets certain conditions the short-circuit operators are enabled
automatically.
In this unit, a Vector class will be used. The Vector class represents a
two-dimensional vector and already overloads arithmetic operators and
the true and false operators. The Vector class will be updated to include
overloading of the four logical operators for Boolean operators.
[DefaultMemberAttribute("Item")]
[SerialisableAttribute()]
public class Vector : ICloneable, ISerialisable, IDisposable
At least one of the operands must be of the same type as the containing
class. This means that by providing the correct signature, you can permit
logical operations between two classes of differing types.
The three binary Boolean operators can be added to the Vector class
using the syntax described above. When determining the results of each,
a vector will be deemed to equate to true if either of the co-ordinates is
non-zero. If both the X and Y properties are zero, the vector will be
159
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Analysis:
Using similar code, we can add the Boolean OR and XOR operators to
the Vector class. Add the following two operator overloads to the class
to implement the two logical functions.
160
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Only one unary Boolean logical operator exists. This is the NOT
operator (!) that switches a Boolean value between true and false. When
overloaded using the unary syntax below, the value returned should be
the opposite of the Boolean representation of the object. As with other
unary operators, the type of the operand provided must be the same as
the class that the declaration appears within.
The NOT operator for the Vector class will examine the contents of the
X and Y properties. As described above, if both co-ordinates are zero,
the Boolean value for the object is false. However, as this is the NOT
operator, we will perform the check and return true only when both
values are zero. Add the following code to the class to provide the NOT
operator:
161
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
To test that the operator is working correctly, modify the Main method
as follows:
The class must overload the normal logical operators (& and |)
with the operation returning a value of the same type as the
containing class. Each parameter of the operator must also be of
the type of the containing class.
The true and false operators must be overloaded.
When the operator is invoked, the true or false operators are used
to determine the status of the first operand. If this guarantees an
outcome from the operation, the result is returned immediately.
When the state of the first operand does not force an outcome, the
AND or OR operator is used for the two values to determine the
result.
The Vector class already includes overloaded true and false operators.
To enable the short-circuit operators, one need to add the correct
signature for the AND and OR operators. As these must return a Vector
result that can be evaluated as either true or false according to the
results, this will return (0,0) if the operation equates to false and (1,1)
162
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
for true. Modify the code for the existing & and | operator overloads as
follows:
You can test that the short-circuit operators are correct by modifying the
Main method of the program. However, as the operators do not return a
Boolean value, an if statement is required in order to test the results of
the operations. This is demonstrated in the following code.
163
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
else
{
Console.WriteLine("v1 && v2 = false"); // Outputs "v1 && v2 =
false"
}
if (v1 || v2)
{
Console.WriteLine("v1 || v2 = true"); // Outputs "v1 || v2 = true"
}
else
{
Console.WriteLine("v1 || v2 = false");
}
}
4.0 CONCLUSION
Vector class is used to represent a real vector. Its methods can be used to
perform vector operations and data manipulation.
8.0 SUMMARY
164
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
165
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
1.2 Objectives
3.0 Main Content
3.1 Adding True and False Operators
3.2 Overloading True and False
3.2.1 Adding True and False to the Vector Class
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
2.0 OBJECTIVES
The default behaviour of any class is to provide no support for the true
and false operators. This means that if an attempt is made to evaluate an
object of such a class as a Boolean the code will fail to compile. This
can be demonstrated by using a Vector object as the condition in an if
166
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
The syntax for overloading the true and false operators is similar to that
of other unary operators. Two limitations exist. Firstly, the return value
must be a Boolean. Secondly, it is invalid to overload only one of the
two operators; if the true operator is overloaded than so must be false
and vice versa.
167
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
}
else
{
return false;
}
}
public static bool operator false(Vector v)
{
if ((v.X == 0) && (v.Y == 0))
{
return true;
}
else
{
return false;
}
}
Analysis:
Now that the two operators have been added, you should be able to
compile and execute the Main method described above. As the vector's
X and Y co-ordinates are not zero, the code outputs the text "True". If
you modify the Vector's declaration as follows, the code will output
“False” instead.
The following are the examples of true and false operator overloading:
168
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
{
return ( e == null ) ? false : e.b;
}
public bool b;
if ( myTrue )
{
System.Console.WriteLine( "true" );
}
else
{
System.Console.WriteLine( "false" );
}
if ( myFalse )
{
System.Console.WriteLine( "true" );
}
else
{
System.Console.WriteLine( "false" );
}
if ( myNull )
{
System.Console.WriteLine( "true" );
}
else
{
169
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
System.Console.WriteLine( "false" );
}
}
}
Output:
True
False
False
using System;
public struct Complex
{
public Complex( double real, double imaginary ) {
this.real = real;
this.imaginary = imaginary;
}
170
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Output:
cpx1 is true
cpx2 is false
using System;
class TwoDimension {
int x, y;
public TwoDimension() {
x = y = 0;
}
public TwoDimension(int i, int j) {
x = i;
y = j;
}
// Overload true.
public static bool operator true(TwoDimension op) {
if((op.x != 0) || (op.y != 0))
return true; // at least one coordinate is non-zero
else
return false;
}
// Overload false.
public static bool operator false(TwoDimension op) {
if((op.x == 0) && (op.y == 0))
return true; // all coordinates are zero
else
return false;
}
171
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
return op;
}
// Show X, Y, Z coordinates.
public void show()
{
Console.WriteLine(x + ", " + y);
}
}
class MainClass {
public static void Main() {
TwoDimension a = new TwoDimension(5, 6);
TwoDimension b = new TwoDimension(10, 10);
TwoDimension c = new TwoDimension(0, 0);
Console.Write("Here is a: ");
a.show();
Console.Write("Here is b: ");
b.show();
Console.Write("Here is c: ");
c.show();
Console.WriteLine();
if(a)
Console.WriteLine("a is true.");
else
Console.WriteLine("a is false.");
if(b)
Console.WriteLine("b is true.");
else
Console.WriteLine("b is false.");
if(c)
Console.WriteLine("c is true.");
else
Console.WriteLine("c is false.");
172
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
Console.WriteLine();
}
}
Output:
Here is a: 5, 6
Here is b: 10, 10
Here is c: 0, 0
a is true.
b is true.
c is false.
4.0 CONCLUSION
173
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
5.0 SUMMARY
174
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
CONTENTS
1.0 Introduction
2.0 Objectives
5.0 Main Content
5.1 Conversion of Data Types
5.2 Creating an Implicit Conversion Operator
5.2.1 Adding Double Conversion to the Vector Class
5.3 Creating an Explicit Conversion Operator
5.3.1 Adding Single Conversion to the Vector Class
5.4 Indexers
5.4.1 Creating an Indexer
5.4.2 Creating a New Array-Like Class
5.4.2.1Adding the Class Variables
5.4.2.2Adding the Constructor
5.4.2.3Adding the Indexer
5.4.3 Creating a Multidimensional Indexer
3.4.4 Creating an Indexer with no Underlying Array
4.0 Conclusion
5.0 Summary
6.0 Tutor-Marked Assignment
7.0 References/Further Reading
1.0 INTRODUCTION
2.0 OBJECTIVES
175
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
When you create a new class, it does not possess the capabilities to be
cast to other data types. Each possible cast must be defined within the
class and declared as either implicit or explicit. As can be seen in the
above example code, the implicit cast can be easier to read and can
provide neater code. However, it is not immediately apparent to the
reader that a conversion is occurring and so implicit casting can hide
problems that would be more apparent if an explicit cast operator were
used.
You may not create operators that convert a class to the object
data type. Conversion to object is provided automatically to
permit boxing and unboxing.
176
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
This unit uses the Vector class. The Vector class represents a two-
dimensional vector and already overloads arithmetic operators, true and
false operators, logical operators and relational operators.
The implicit and explicit cast operators are unary operators and, as such,
are overridden using a similar syntax as other basic unary operators. The
following syntax is for the implicit conversion operator:
The result-type is the data type for the return value of the operation, i.e.
the target type for the cast. The op-type is the data type for the operand
that is to be converted. One of the two data types must be the same as
the class in which the declaration is made.
177
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
The new conversion can be tested using the updated Main method
below. Note the loss of accuracy that occurs when the vector's length is
cast.
float f = (float)v;
Console.WriteLine(f);
}
// Outputs 7.071068
Note: The use of the (float) operator is required in this example as the
conversion has been defined as explicit. Removing this cast operator
causes a compiler error.
3.4 Indexers
178
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
under the same name, with each variable accessed using an index
number provided in square brackets. For example:
thirdItem = items[3];
Indexer is use often to incorporate the square bracket notation for new
classes. This may be because the class is used to store related
information in a similar manner to an array, or simply because the index
number can be useful in a calculation or lookup. Adding an indexer to a
class provides this functionality.
179
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
The new array-like class requires three private variables. Two integer
values will hold the upper and lower boundaries. An array of strings will
also be required to store the items added to the MyArray class. This will
be a zero-based array with the same length as the created MyArray
object. The indexer will interpret the index number supplied and map it
against this underlying array forget and set operations. To add the class
level variables, add the following code to the MyArray class’ code
block:
int _lowerBound;
int _upperBound;
string[] _items;
The constructor for the new class will accept two integer parameters that
define the upper and lower boundaries. These values will be stored in
the two associated class variables. Using these boundaries, the length of
the underlying array can be calculated and the array can be initialised
accordingly. To create the constructor, add the following code to the
class:
Now that the preparation work is complete, we can add the indexer to
the class. For this simple array-like class, the indexer accepts a single
integer parameter containing the index of the string that is being read
from or written to. This index needs to be adjusted to correctly map to
the underlying data before returning the value from the array or writing
the new value into the array. The code to add the indexer is shown
below. Note that as with property declarations, the set accessor uses the
180
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
'value' variable to determine the value that has been assigned by the
calling function:
Analysis:
The new class can be tested using the Main method of the program.
Open the Program class and add the following code to create a new
instance of MyArray and to populate it with values.
181
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
182
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
4.0 CONCLUSION
Conversion operators are those that involve converting from one data
type to another through assignment. There are implicit and explicit
conversions. Implicit conversions are those that involve direct
assignment of one type to another. Explicit conversions are conversions
that require one type to be casted as another type in order to perform the
conversion. Conversions that may cause exceptions or result in loss of
data as the type is converted should be handled as explicit conversions.
5.0 SUMMARY
183
CIT383 INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING
184