You are on page 1of 17

Domasi College of Education

Unit 2

Classes, Objects and Class


Diagrams

Introduction
In the previous unit, you defined Object-Oriented
Programming (OOP) and stated the characteristics of
OOP. In this unit, you are going to be introduced to
classes, objects and class diagrams.

Success Criteria
By the end of this Unit, you should be able to:
 define classes, objects and class diagrams
 create classes and objects
 state benefits of class diagrams
 translate a real-life problem into an object
oriented design using class diagrams

Key Words
You will find the following key words or phrases in this
unit: class, object, attribute, multiplicity, class
diagram. Watch for these and make sure that you
understand what they mean and how they are used in
the unit.

Computer Programming II, Object-Oriented 2-0


Domasi College of Education

Classes and Objects

You may wish to note that for you to understand


classes and objects you should first consider the
following illustration:

Classes Objects
Animal Dog
Cat
Goat
Cow
Fruit Pawpaw
Orange
Mango
Lemon

From the illustration above, you will notice that Fruit


is a class with the following objects: pawpaw, orange,
mango and lemon. Animal is also a class with objects
dog, cat, goat and cow. Therefore, in this case every
object has a class.

So, object is defined as an instance of a class. An object


can also be defined as anything/entity that has state or
attribute and behavior. Attributes are defined by
variables. For example, a dog is an object because it
has states or attributes like color, name, etc. The dog
has also behaviors like wagging the tail, barking,
eating, etc. In this case, behaviors are actions
supported by the object.

In Java programming, these behaviors are called


methods. You will learn more about methods in unit
4.
A class on the other hand, is defined as a
template/blueprint that describes the behavior/state
that the object of its type supports.

Creating a Class and Attributes

Computer Programming II, Object-Oriented 2-1


Domasi College of Education

Now that you have understood classes then you will


learn how classes are created in Java.

In Java, to create a class you must use the keyword


class. The first letter of the class name must be in
Upper Case.

Example:

public class Domasi {


int x = 5;
int y = 3;
}
From the above example, public is an access modifier
and Domasi is the class name. Note that the class body
is surrounded by braces {}.

The class Domasi has two attributes which are x and y


that have also been created.

Where several words are used to form a name of the


class, each inner word's first letter should be in Upper
Case.

Example:

public class NalikuleCampus {


int x = 5;
int y = 3;
}

Types of Variables in Java


There are three types of variables in Java namely:

 Local Variables
 Instance Variables
 Static Variables (Class Variables)
Local Variable: This is a variable which is defined
within a block or method or constructor.
Example:
public class Nalikule{
public void pupAge() {
//creating local variable inside the method pupAge()
int x = 5
Computer Programming II, Object-Oriented 2-2
Domasi College of Education

System.out.println("Puppy age is : " + age);


}

You may wish to note that these variables are created


when the block is entered or the function is called and
destroyed after exiting from the block or when the call
returns from the function.

The scope of these variables exists only within the


block in which the variable is declared, that is, we can
access these variables only within that block.

Read Unit 4 to understand methods and constructors.

Instance Variables: These are non-static variables and


are declared in a class outside any method,
constructor or block.
Example:
class Domcol{
int x; //instance variable created outside the
method pupAge()
public void pupAge() {
}
}
As instance variables are declared in a class, these
variables are created when an object of the class is
created and destroyed when the object is destroyed.

Instance Variable can be accessed only by creating


objects.

Class Variables: These are declared similarly as


instance variables. The difference is that static
variables are declared using the static keyword within
a class outside any method constructor or block.

Example:
class Domcol{
static int x; //static variable created outside
the method pupAge()
public void pupAge() {
}
}
Computer Programming II, Object-Oriented 2-3
Domasi College of Education

Static variables are created at the start of program


execution and destroyed automatically when execution
ends.

Creating an Object
In order to create an object, you must first of all create
a class.

Let us use the above classes to create an object. In


order to achieve this, we specify the class name,
followed by the object name, and use the keyword new
as follows:

Domasi myObj = new Domasi();


NalikuleCampus myObj = new Domasi();

Accessing Attributes
You may be interested to note that in order to access
attributes you are supposed to create an object of the
class, and use the dot syntax (.):

The following example creates an object of the Dog


class, with the name myObj. We use the x attribute on
the object to print its value:

public class Dog {


int x = 5;

public static void main(String[] args) {


Dog myObj = new Dog();
System.out.println(myObj.x);
}
}

Computer Programming II, Object-Oriented 2-4


Domasi College of Education

Self-Evaluation Activity 2-a


1. What is wrong with the following Java code?

public class dog {


int x = 5;

public static void main(String[] args) {


Dog myObj = new Dog();
System.out.println(myObj.x);
}

2. How do you create an object?

Answers to this activity are at the end of the unit.

Practise Activity
Assign and print the roll number, phone number and
address of two students having names "Sam" and
"John" respectively by creating two objects of class
'Student'.

Computer Programming II, Object-Oriented 2-5


Domasi College of Education

Unified Modeling Language (UML) Class


Diagrams
You may wish to note that when designing a system,
there is a need to have a conceptual understanding of
the system — that is, what classes do I need? What
functionality and information will these classes have?
How do they interact with one another? Who can see
these classes? And so on. Now, this is where the issue
of class diagrams comes in.

Definition 2.1
A class diagram is a static structure that gives an
overview of a software system by displaying classes,
attributes, operations, and their relationships between
each other.

This Diagram includes the class name, attributes, and


operation in separate designated compartments.

Benefits of class diagrams

JavaTPoint (n. d), identifies the following benefits:


 It can represent the object model for complex
systems.
 It reduces the maintenance time by providing an
overview of how an application is structured
before coding.
 It provides a general schematic of an application
for better understanding.
 It represents a detailed chart by highlighting the
desired code, which is to be programmed.
 It is helpful for the stakeholders and the
developers.

Components of class diagrams

It has upper section which contains a name of the


class, middle section which contains the attributes and
the lower section which contains methods or
operations.

Computer Programming II, Object-Oriented 2-6


Domasi College of Education

Class Name

Attributes

Methods

Suppose, we have a Person class then this can be


modeled as follows:

Person Class

-name: String

+getName(): String
+ setName(name): void

You should note that the above example has used two
visibility markers to signify who can access the
information contained within a class. The following are
the some of the visibility markers:

 private visibility, denoted with a - sign, hides


information from anything outside the class
partition.
 public visibility, denoted with a + sign, allows all
other classes to view the marked information.
 protected visibility, denoted with a # sign, allows
child classes to access information they
inherited from a parent class.

Relationships between Classes


Besides using rectangles to represent classes, class
diagrams include arrows to represent relationships
among classes.

The following are arrows to represent relationships


among classes:

Computer Programming II, Object-Oriented 2-7


Domasi College of Education

Now, let us describe the types of relationships.

1. Dependency: It is a semantic relationship


between two or more classes where a change
in one class cause changes in another class.
It forms a weaker relationship.

Example:

2. Generalization: A generalization is a
relationship between a parent class
(superclass) and a child class (subclass). In
this, the child class is inherited from the
parent class.

Example:

Computer Programming II, Object-Oriented 2-8


Domasi College of Education

3. Association: It describes a static or physical


connection between two or more objects. It
depicts how many objects are there in the
relationship.

Example:

Other types of relationships

1. Aggregation: Aggregation is a special type


of association that models a whole- part
relationship between aggregate and its
parts.

Example:

From the above diagram, the company encompasses a


number of employees, and even if one employee
resigns, the company still exists.

Computer Programming II, Object-Oriented 2-9


Domasi College of Education

2. Composition: The composition is a subset


of aggregation. It portrays the dependency
between the parent and its child, which
means if one part is deleted, then the
other part also gets discarded. It
represents a whole-part relationship.

Example:

From the above diagram a contact book consists of


multiple contacts, and if you delete the contact book,
all the contacts will be lost.

Note that the above examples of relationships have


no middle and lower sections. Only upper section
has been considered. However, you can include
them in your relationships.

Multiplicity

It defines a specific range of allowable instances of


attributes. In case if a range is not specified, one is
considered as a default multiplicity.

Computer Programming II, Object-Oriented 2-10


Domasi College of Education

From the above diagram, multiple patients are


admitted to one hospital. Note the indicator shown on
the above diagram (*).

The table below shows indicators and their meanings:

Indicator Meaning
0..1 Zero or one
1 One only
0..* Zero or more
n Only n (where n>1)
0..n Zero to n (where n>1)
1..n One to n (where n>1)
1..* * One or more

The following example of an ATM system summarizes


Unified Modeling Language (UML) class diagrams:

Computer Programming II, Object-Oriented 2-11


Domasi College of Education

You should take note that TutorialsPoint (n. d),


outlines the following points that should be
remembered when drawing a class diagram:

 The name of the class diagram should be


meaningful to describe the aspect of the system.
 Each element and their relationships should be
identified in advance.
 Responsibility (attributes and methods) of each
class should be clearly identified
 For each class, minimum number of properties
should be specified, as unnecessary properties
will make the diagram complicated.
 Use notes whenever required to describe some
aspect of the diagram. At the end of the drawing
it should be understandable to the
developer/coder.
 Finally, before making the final version, the
diagram should be drawn on plain paper and
reworked as many times as possible to make it
correct.
Computer Programming II, Object-Oriented 2-12
Domasi College of Education

Self-Evaluation Activity 2-b


1. State four benefits of class diagrams.
2. What do you understand by the term multiplicity?

Answers to this activity are at the end of the unit.

Summary
In this unit, you have been introduced to classes,
objects and class diagrams. You have also been
introduced to multiplicity.
 object is defined as an instance of a class
 class is defined as a template/blueprint that
describes the behaviour/state that the object of
its type supports
 a class diagram is a static structure that gives
an overview of a software system by displaying
classes, attributes, operations, and their
relationships between each other
 multiplicity is defined as a specific range of
allowable instances of attributes
Reflection
Which part of this unit is most challenging to you?
Why? Do you need special assistance?

Computer Programming II, Object-Oriented 2-13


Domasi College of Education

Unit 2 Test
1. Create a class named 'Student' with String
variable 'name' and integer variable 'roll_no'.
Assign the value of roll_no as '2' and that of
name as "John" by creating an object of the class
Student.
2. A company consists of departments.
Departments are located in one or more offices.
One office acts as a head quarter. Each
department has a manager who is recruited from
the set of employees. Draw a class diagram
which consists of all the classes in your system
their attributes and operations, relationships
between the classes, multiplicity specifications,
and other model elements that you find
appropriate.

Answers to this activity are at the end of the unit.

Computer Programming II, Object-Oriented 2-14


Domasi College of Education

Answers to Unit 2 Activities


Answers to Activity 2-a

1. The class name has started with a lower case


instead of upper case. There is also no closing
brace. The program is supposed to be as follows:
public class Dog {
int x = 5;
public static void main(String[] args) {
Dog myObj = new Dog();
System.out.println(myObj.x);
}
}

2. In order to create an object, specify the class


name, followed by the object name, and use the
keyword new as follows:
Car myObj = new Car();

Answers to Activity 2-b


1. Choose any four:
 It can represent the object model for
complex systems.
 It reduces the maintenance time by
providing an overview of how an
application is structured before
coding.
 It provides a general schematic of an
application for better understanding.
 It represents a detailed chart by
highlighting the desired code, which
is to be programmed.
 It is helpful for the stakeholders and
the developers.

Computer Programming II, Object-Oriented 2-15


Domasi College of Education

2. It defines a specific range of allowable


instances of attributes.

Answers to Unit 2 Test

1. Below is the solution:


class Student{
String name;
int roll_no;
}

class Ans{
public static void main(String[] args){
Student s = new Student();
s.name = "John";
s.roll_no = 2;
System.out.println("Name is "+s.name+"
and roll number is "+s.roll_no);
}
}

2. Here is the solution:

Computer Programming II, Object-Oriented 2-16

You might also like