Cos 2101 Lecture 4 Classes and Objects
Cos 2101 Lecture 4 Classes and Objects
OBJECT ORIENTED
PROGRAMMING
KAMPALA INTERNATIONAL UNIVERSITY
COURSE OBJECTIVES
The objective of this course is
• To provide object oriented concepts through which robust, secured and
reusable software can be developed.
• To understand classes and objects are and how they relate to each other
in the development.
• To understand object oriented principles like abstraction, encapsulation,
inheritance, polymorphism and apply them in solving problems.
• To understand the principles of inheritance and polymorphism and
demonstrate how they relate to the design of abstract classes.
UNIT 1
JAVA PROGRAMMING:
• History of Java, comments, Java keywords, Data types, Variables,
Constants, Scope and Lifetime of variables, Operators, Enumerated
types,
• Control flow- block scope, conditional statements, loops, break and
arrays,
• Simple java stand alone programs, class, object, and its methods
constructors, methods, static fields and methods,
• Access control, this reference, overloading constructors, recursion,
exploring string class, garbage collection.
COURSE OUTCOMES
1. A competence to design, write, compile, test and execute straight
forward programs using a high level language;
2. An appreciation of the principles of object oriented programming;
3. Be able to implement, compile, test and run Java programs
comprising more than one class, to address a particular software
problem.
4. Demonstrate the ability to employ various types of selection
constructs in a Java program. Be able to employ a hierarchy of Java
classes to provide a solution to a given set of requirements.
USING CLASSES AND OBJECTS
• When you think in an object-oriented manner, everything is an object, and
every object is a member of a class.
• You can think of any inanimate physical item e.g desk, computer, building,
living things e.g pet fish, your sister etc, events e.g stock purchase,
graduation party etc as objects.
• Every object is a member of a more general class example your desk is an
instance of the Desk class and your fish is an instance of the Fish class.
• An object is an instantiation of a class, or one tangible example of a class.
Your goldfish, my guppy, and the zoo’s shark each constitute one
instantiation of the Fish class.
USING CLASSES AND OBJECTS
• Objects can be members of more than one class. For example,
your goldfish is not just a Fish, but also a Vertebrate and an
Animal.
• The concept of a class is useful because it provides reusability.
• Objects gain their attributes from their classes, and all objects
have predictable attributes because they are members of certain
classes. For example, if you are invited to a graduation party, you
automatically know many things about it. You assume there will
be a starting time, a certain number of guests, and some quantity
of food.
USING CLASSES AND OBJECTS
• Objects have methods associated with them, and every object
that is an instance of a class is assumed to possess the same
methods.
• For example, for all Party objects, a date and time are set at
some point. In a program, you might name these methods
setDate () and setTime (). The getDate () and getTime ()
method are used to find out the date and time of any Party
object.
• Method names that begin with get and set are very typical.
USING CLASSES AND OBJECTS
• Party class, myGraduationParty object and data methods
setDate() and setTime()
• e.g. myGraduationParty.setDate("May 12");
• Within any object-oriented program, you are continuously
making requests to objects’ methods and often including
arguments to send information as part of those requests.
• Within object-oriented programs, methods are often called
upon to return a piece of information to the source of the
request.
USING CLASSES AND OBJECTS
• You can identify a class that is an application because it contains a public static
void main() method. The main() method is the starting point for any application.
You will write and use many classes that do not contain a main() method—these
classes can be used by other classes that are applications.
• A Java application can contain only one method with the header public static void
main(String [ ] args). If you write a class that imports another class, and both
classes have a public static void main(String [] args) method, your application will
not compile.
• You don’t need to create every class you use. Often, you will write programs that
use classes created by others. For example, many programs you have seen so far
have used the System class. You did not have to create it or its println () method;
both were provided for you by Java’s creators.
CREATING A CLASS
• When you create a class, you must assign a name to the class,
and you must determine what data and methods will be part
of the class.
• To begin, you create a class header with three parts:
• An optional access specifier
• The keyword class
• Any legal identifier you choose for the name of your class
—starting with an uppercase letter is conventional
• Example is public class Employee
CREATING A CLASS
• The most liberal form of access is public. The
keyword public is a class modifier. Classes that are
public are accessible by all objects.
• Public classes also can be extended, or used as a basis
for any other class.
• After writing the class header public class, you write
the body of the class between a set of curly braces.
• The body contains the data and methods for the class.
CREATING A CLASS
• The data components of a class are often referred to as
data fields to help distinguish them from other variables
you might use. Data fields are variables you declare
within a class but outside of any method
• The use of static in a data field means a single value
would be shared by all objects that are eventually
instantiated. A nonstatic field is an instance variable for
the class because one copy exists for each object
instantiation.
CREATING A CLASS
• private class provides the highest level of security. Assigning
private access to a field means that no other classes can access
the field’s values, and only methods of the same class are allowed
to set, get, or otherwise use private variables.
• The principle used in creating private access is sometimes called
information hiding and is an important component of object-
oriented programs.
• A class’s private data can be changed or manipulated only by a
class’s own methods and not by methods that belong to other
classes.
CREATING A CLASS
• In contrast to fields, which are usually private, most class
methods are public.
• The resulting private data/public method arrangement
provides a means for you to control outside access to your
data—only a class’s nonprivate methods can be used to
access a class’s private data.
• The way in which the nonprivate methods are written
controls how you use the private data.
CREATING A CLASS
• In summary, when you create classes from which you
will instantiate objects:
• The class’s data fields are most often private.
• The class’s methods are most often not static.
• Occasionally, you might have a reason to make a field
public, and when you want to use a nonchanging value
without being required to create an object, you make
the field both static and final.
CREATING INSTANCE METHODS IN A CLASS
• Declaring a class does not create any actual objects. A class is just an
abstract description of what an object will be like if any objects are ever
actually instantiated.
• You can create a class with fields and methods long before you
instantiate any objects that are members of that class.
• A two-step process creates an object that is an instance of a class. First,
you supply a type and an identifier—just as when you declare any
variable—and then you allocate computer memory for that object.
• int someValue -you notify the compiler that an integer named someValue
will exist, and you reserve computer memory for it at the same time.
DECLARING OBJECTS AND USING THEIR
METHODS
• Employee someEmployee; someEmployee can be any legal identifier.
When you declare the someEmployee instance of the Employee class,
you are notifying the compiler that you will use the identifier
someEmployee. However, you are not yet setting aside computer
memory in which the Employee named someEmployee might be stored
—that is done automatically only for primitive type variables.
• To allocate the needed memory for an object, you must use the new
operator. Two statements that actually complete the process by setting
aside enough memory to hold an Employee are as follows:
• Employee someEmployee;
• someEmployee = new Employee();
DECLARING OBJECTS AND USING
THEIR METHODS
• Instead of using two statements, you can declare and reserve memory for
someEmployee in one statement, as in the following:
Employee someEmployee = new Employee();
• Employee is the object’s type (as well as its class)
• someEmployee is the name of the object
• The equal sign is the assignment operator, so a value is being assigned to
someEmployee in the declaration.
• The new operator is allocating a new, unused portion of computer memory for
someEmployee.
• The Employee() method is a constructor, a special type of method that
creates and initializes objects.
AN INTRODUCTION TO USING
CONSTRUCTORS
• When you create a class, such as Employee, and instantiate an object with a
statement such as the following, you actually are calling the Employee class
constructor that is provided by default by the Java compiler:
• Employee chauffeur = new Employee();
• A constructor establishes an object; a default constructor is one that requires no
arguments.
• A default constructor is created automatically by the Java compiler for any class
you create whenever you do not write your own constructor.
• When the prewritten, default constructor for the Employee class is called, it
establishes one Employee object with the identifier provided.
AN INTRODUCTION TO USING
CONSTRUCTORS
• The automatically supplied default constructor
provides the following specific initial values to an
object’s data fields:
• Numeric fields are set to 0 (zero).
• Character fields are set to Unicode ‘\u0000’.
• Boolean fields are set to false.
• Fields that are objects themselves (for example,
String fields) are set to null (or empty).
AN INTRODUCTION TO USING
CONSTRUCTORS
• You can place the constructor anywhere inside the class, outside of any other
method.
• Typically, a constructor is placed with the other methods.
• Often, programmers list the constructor first because it is the first method used
when an object is created.
• Normally, you declare constructors to be public so that other classes can
instantiate objects that belong to the class. When you write a constructor for a
class, you no longer have access to the automatically created version.
• Any constructor you write:
• Must have the same name as the class it constructs
• Cannot have a return type—not even void
CREATING CONSTRUCTORS WITH
PARAMETERS
• The Employee class with a default constructor that initializes the empNum field
public class Employee
{
private int empNum;
Employee()
{
empNum = 999;
}
}
Employee partTimeWorker = new Employee();
CREATING CONSTRUCTORS WITH
PARAMETERS
• The Employee class with a constructor that accepts a value
public class Employee
{
private int empNum;
Employee(int num)
{
empNum = num;
}
}
Employee partTimeWorker = new Employee(881);
CREATING CONSTRUCTORS WITH
PARAMETERS
• The Employee class that contains two constructors
public class Employee
{
private int empNum;
Employee(int num)
{
empNum = num;
}
Employee()
{
empNum = 999;
}}
CREATING CONSTRUCTORS WITH
PARAMETERS
• You can use constructor arguments to initialize field
values, but you also can use them for any other purpose.
• For example, you could use the presence or absence of
an argument simply to determine which of two possible
constructors to call, yet not make use of the argument
within the constructor.
• As long as the constructor parameter lists differ, the
constructors are not ambiguous.
LEARNING ABOUT THE THIS REFERENCE
• When you start creating classes, they can become large very quickly. Besides data fields, each
class can have many methods, including several overloaded versions. On paper, a single class
might require several pages of coded statements.
• When you instantiate an object from a class, memory is reserved for each instance field in the
class.
• if a field is static, then only one copy of the field exists, and all objects created have the same
value for that field. Fields that hold unique values for each object are not defined as static.
• When you create a method that uses a nonstatic field value for a class—for example, to get or
set the field value—the method must be nonstatic. That means it performs in a different way
for each object.
• When you use a nonstatic method, you use the object name, a dot, and the method name—for
example, aWorker.getEmpNum() or anotherWorker.getEmpNum().
LEARNING ABOUT THE THIS REFERENCE
• The compiler accesses the correct object’s field because every time you call a nonstatic method, a
reference—an object’s memory address—is implicitly understood.
• The reference to an object that is passed to any object’s nonstatic method is called the this
reference; this is a reserved word in Java.
• Only nonstatic instance methods have a this reference.
• The first method simply uses the this reference without your being aware of it; the second method
uses the this reference explicitly. Both methods return the empNum of the object used to call the
method.
• Usually, you neither want nor need to refer to the this reference within the instance methods that
you write, but the this reference is always there, working behind the scenes so that the data field
for the correct object can be accessed.
• On a few occasions, you must use the this reference to make your classes work correctly;
USING THE THIS REFERENCE TO MAKE OVERLOADED
CONSTRUCTORS MORE EFFICIENT
USING STATIC FIELDS
• Methods you create to use without objects are static.
• Most methods you create within a class from which objects will be
instantiated are nonstatic.
• Static methods do not have a this reference because they have no
object associated with them; therefore, they are called class methods.
• You can also create class variables, which are variables that are shared
by every instantiation of a class. Whereas instance variables in a class
exist separately for every object you create, there is only one copy of
each static class variable per class.
USING CONSTANT FIELDS
• Sometimes a data field in a class should be constant.
• Because it is static, all objects share a single memory
location for the field, and because it is final, it cannot
change during program execution.
• A nonstatic final field’s value can be assigned a value
in a constructor. For example, you can set it using a
constant, or you can set it using a parameter passed
into the constructor.
USING CONSTANT FIELDS
• You can use the keyword final with methods or classes
as well as with fields. When used in this manner, final
indicates limitations placed on inheritance.
• Fields that are final also can be initialized in a static
initialization block.
• Fields declared to be static are not always final.
Conversely, final fields are not always static.
USING IMPORTED, PREWRITTEN
CONSTANTS AND METHODS
• If you write Java programs for an organization, you most
likely will create dozens or hundreds of custom-made classes
eventually.
• However, many classes do not require customization for
specific businesses. Instead, they are commonly used by a
wide variety of programmers. Rather than have each Java
programmer “reinvent the wheel,” the creators of Java have
produced hundreds of classes for you to use in your
programs.
USING IMPORTED, PREWRITTEN
CONSTANTS AND METHODS
• You already have used several of these
prewritten classes; for example, you have
used the System class to produce output
• Each of these classes is stored in a package,
or a library of classes, which is simply a
folder that provides a convenient grouping
for classes.
USING IMPORTED, PREWRITTEN
CONSTANTS AND METHODS
Java has two categories of packages:
• The java.lang package is implicitly imported into every program
you write. The classes it contains are fundamental classes that
provide the basis of the Java programming language. The System
class, which you have used to access print() and println (), is an
automatically imported class in the java.lang package. You will
learn about many other fundamental classes later. Some
references list a few other Java classes as also being
“fundamental,” but the java.lang package is the only
automatically imported, named package.
USING IMPORTED, PREWRITTEN
CONSTANTS AND METHODS
• All other Java packages are available only if you
explicitly name them within your program. These
packages contain the optional classes. For example,
when you use JOptionPane, you must import the
javax.swing package into your program, and when you
use the LocalDate class, you must import the java.time
package,
THE MATH CLASS
• The class java.lang.Math contains constants and methods that you can use to
perform common mathematical functions. All of the constants and methods in the
Math class are static—they are class variables and class methods. In other words,
you do not create any Math objects when you use the class.
• public final static double PI = 3.14159265358979323846;
• Notice that PI is:
• public, so any program can access it directly
• final, so it cannot be changed
• static, so only one copy exists and you can access it without declaring a Math
object
• double, so it holds a floating-point value
THE MATH CLASS
THE MATH CLASS
THE MATH CLASS
• Because all constants and methods in the Math class are classwide
(that is, static), there is no need to create an instance of the Math class.
You cannot instantiate objects of type Math because the constructor
for the Math class is private, and your programs cannot access the
constructor.
• Unless you are a mathematician, you won’t use many of these Math
class methods, and it is unwise to do so unless you understand their
purposes. For example, because the square root of a negative number
is undefined, if you display the result after the method call
imaginaryNumber = Math.sqrt(-12);, you see NaN
IMPORTING CLASSES THAT ARE NOT IMPORTED
AUTOMATICALLY
• An alternative to importing a class is to import an entire package
of classes. You can use the asterisk ( * ) as a wildcard symbol,
which indicates that it can be replaced by any set of characters.
• In a Java import statement, you use a wildcard symbol to
represent all the classes in a package.
• The import statement does not move the entire imported class or
package into your program, as its name implies. Rather, it simply
notifies the program that you will use the data and method names
that are part of the imported class or package.
IMPORTING CLASSES THAT ARE NOT IMPORTED
AUTOMATICALLY
• Two of the ways that you can group classes are by using composition
and by nesting classes.
1. Composition
• The fields in a class can be simple data types such as int and double,
but they also can be class types.
• Composition describes the relationship between classes when an
object of one class is a data field within another class.
• When you use an object as a data member of another object, you must
remember to supply values for the contained object if it has no default
constructor.
UNDERSTANDING COMPOSITION AND NESTED
CLASSES
NESTED CLASSES
• Every class you have studied so far has been stored in its own file, and the filename has always
matched the class name. In Java, you can create a class within another class and store them
together; such classes are nested classes. The containing class is the top-level class. There are
four types of nested classes:
• static member classes—A static member class has access to all static methods of the top-level
class.
• Nonstatic member classes, also known as inner classes—This type of class requires an instance;
it has access to all data and methods of the top-level class.
• Local classes—These are local to a block of code.
• Anonymous classes—These are local classes that have no identifier.
The most common reason to nest a class inside another is because the inner class is used only by
the top-level class; in other words, it is a “helper class” to the top-level class. Being able to package
the classes together makes their connection easier to understand and their code easier to maintain.
NESTED CLASSES
TEXTBOOKS/ REFERENCE BOOKS
1. Farell, J. (2023). Java Programming, 6. Auflage, Course Technology, Cengage
Learning, USA.
2. Murach, J. (2015). Murach's Java Programming. Mike Murach & Associates.
3. Charatan, Q., & Kans, A. (2006). Java in two semesters. McGraw-Hill.
4. Harvey M. Deitel and P. J. Deitel (2007). Java How to Program, 7th Edition-
Prentice Hall
5. Malik D. S. (2003). Java Programming: From Problem Analysis to Program
Design. Course Technology, Cengage Learning, USA.
6. Liang, Y. D. (2003). Introduction to Java programming. Pearson Education India.
7. Object Oriented Programming through Java, P. J. Radha Krishna, Universities
Press.
8. Thinking in Java, Bruce Eckel, PE
9. Programming in Java, S. Malhotra and S. Choudhary, Oxford Universities Press.