Writing Classes
using Object Oriented Programming Approach
Coding with
RECAP: CLASSES IN JAVA
String
Class Wrapper
_______ _______
Import (some are imported _______
Scanner _______ Random
…
by default) Class Class Class
_______ _______ _______
_______ _______ _______
Student JAVA library
_______ (PREDEFINED CLASSES)
_______ Employee
_______
_______
Classes created by JAVA users
(USER DEFINED CLASSES)
RECAP: UML CLASS DIAGRAM
Example:
ClassName
Attribute1: data type
Attribute2: data type
Attribute3: data type Student
. -studName: String
. -matricNumber: String
method1() : data type -marks: double
method2() : data type + Student(String name, String matric)
method3() : data type + setMarks(double studentMarks):void
. + determineGrade () : String
. + displayInfo() : void
A STUDENT CLASS AND TWO INSTANCES
Student
-studName: String
-matricNumber: String
Instance of -marks: double Instance of
class + Student(String name, String matric) class
Student + setMarks(double studentMarks):void Student
+ determineGrade () : String
+ displayInfo() : void
124
123 student2 student2 : Student
student1 student1 : Student 124
studName = “Anas”
123 matricNumber = “93048”
studName = “Ah Cheong”
matricNumber = “93047” marks = 95
marks = 80
student2 object
student1 object
UML CLASS DIAGRAM & OBJECT NOTATION
Circle Class name
-radius: double Data fields
+Circle() Constructors and
+Circle(radius: double) methods
122 123 +calculateArea(): double
124
circle1 circle2
circle1 circle3
123 circle2: Circle 124 circle3: Circle UML notation
122 circle1: Circle
for objects
radius = 1.0 radius = 25.0 radius = 100.0
5
HOW TO DEFINE CLASS?
Use class keyword to define a class and put the class members inside curly braces - { }.
ClassName
Attribute1: data type
Attribute2: data type
.
.
STEP 1 STEP 2 STEP 3
method1() : data type
• Define class • Define • Define method2() : data type
header attributes methods .
.
STEP 1: DEFINE CLASS HEADER
• Syntax to define class header:
<accessModifier> class <ClassName>
{
<instance variable(s)>
<member method(s)>
}
where:
- <accessModifier> – determine access rights for the class and its members.
- <className> – class name that we want to define.
ACCESS MODIFIERS
Access Modifiers Description
public The class/attributes/methods can be accessed by the
class/methods of the same class and other classes
private The attributes/methods can ONLY be accessed within
the class where the attributes/methods are defined
STEP 1: DEFINE CLASS HEADER: EXAMPLE
• Example:
public class Student
{
...
}
• The above class is an empty class and has no functionality.
• To make it work, we must include instance variables and member methods in curly braces
(Step 2 and Step 3).
STEP 2: DEFINE ATTRIBUTE(S)
• Syntax to define attribute(s):
<accessModifier> <dataType> <identifierList>;
where:
- <accessModifier> – determine access rights for the
class and its members.
- <dataType> – can be primitive data type or a class type.
- <identifierList> – can contain one or more variable names
of the same data type with or without initialization.
• Define attribute (s) before it can be used in method(s).
STEP 2: DEFINE ATTRIBUTE(S): EXAMPLES
• Examples:
private String name;
Constant
private final double PI = 3.142;
private int age, width, height;
STEP 3: DEFINE METHOD(S)
• Syntax to define method(s):
<accessModifier> <returnType> <methodName>(<parameter(s))>
{
<method body>
}
where:
- <accessModifier> – determine access rights for the method(s).
- <returnType> – can be primitive data type or void.
- <methodName> – user-defined method name.
- <parameter(s)> - a comma-separated list of data types and variable names.
METHODS
Most programs are large enough to be broken down into several
subtasks.
Thus, they are broken down into methods to perform a specific task.
A method is a group of statements that exists within a program for
the purpose of performing a specific task.
Each method is assigned to perform a specific subtask.
13
Structure of method – method header & body
STEP 1 – Define class header
STEP 2 – Define attributes/ variables
Constructor
Method
Setter Method
Define methods
determineGrade ()
Method
displayInfo ()
Method
HOW TO NAME CLASSES AND METHODS?
Class naming tips: Method naming tips:
- Use a noun for the class name. - Use verb for method name.
- Begin the class name with a - Begin the method name with a lowercase
capital letter. letter and capitalize internal words.
RECAP: METHOD DEFINITION
Method definition always contains two parts:
A header
The starting point of the method.
A body
Contain all statements to perform the method’s task.
16
RECAP: TYPES OF METHODS
Methods can return zero or ONE value.
Void methods
Methods that do not have a return type
Value-returning methods
Methods that have a return type
METHOD HEADER
A method definition begins with a method header.
<accessModifier> <returnType> <methodName> (<parameter(s)>)
public void displayInfo ( )
public void showMessage ( ) Void methods
public double depositMoney (double money)
Value-returning
public double calculatePrice (int quantity) methods
1-18
VOID METHOD
• Syntax: Header
<accessModifier> <returnType> <methodName>(<parameter(s)>)
{ Body
<statement(s)> without return expression.
}
Header
• Example: Body
VALUE RETURNING METHOD
• Syntax:
<accessModifier> <returnType> <methodName>(<parameter(s)>)
{
<statement(s)> The return variable data type must have a
type that matches the <returnType>.
return expression.
Header
}
• Example:
Body
METHOD WITH PARAMETER(S)
Syntax for method header:
<accessModifier><returnType><methodName>(dataType variableName, dataType variableName,..)
Note: If more than1 parameters, each parameter is separated with comma (,)
Eg.
public void printStudName(String name)
public double calculateMarks(String matricNumber, double carryMarks, double finalExamMarks )
21
UML CLASS DIAGRAM: EXAMPLE 1
Student
-studName: String
-matricNumber: String
-marks: double Constructor
+ Student(String name, String matric)
+ setMarks(double studentMarks):void Void method
+ determineGrade () : String
+ displayInfo() : void Value returning
method
Void method
COMPLETE CLASS DEFINITION: EXAMPLE 1
STEP 1 – Define class header
STEP 2 – Define attributes/ variables
STEP 3 – Define methods
UML CLASS DIAGRAM: EXAMPLE 2
Rectangle
-width: int
-length: int
-area: int
-perimeter: int
+ Rectangle(int width, int length)
+ calculateArea():int
+ calculatePerimeter () : int
COMPLETE CLASS DEFINITION: EXAMPLE 2
STEP 1 – Define class header
STEP 2 – Define attributes/ variables
STEP 3 – Define methods
CONSTRUCTOR METHOD
• Special methods that are invoked to create objects using the new
keyword.
• Its main purpose is to initialize the object’s data (attributes).
• It is automatically executed when you create objects.
• Constructors must have the same name as the class name.
• A class can have one/several constructors.
CONSTRUCTOR METHOD: METHOD DEFINITION SYNTAX
• Syntax to define a constructor method:
public <ClassName> ( <parameter(s)>)
{
// constructor body
}
• Constructor method definition is the same with other methods.
• Each constructor must have a different number of parameters or parameters of
different types *if there are more than one constructors in a class
• However, constructor method has no return value, not even void!
CONSTRUCTOR METHOD WITH PARAMETER: EXAMPLE
Same name as class
name
(String studentName, String matricNumber)
[Link] = studentName;
[Link] = matricNumber;
CONSTRUCTOR METHOD : THE USE OF ‘THIS’
(String studentName, String matricNumber)
(String studentName, String matricNumber)
[Link] = studentName;
studentName = studentName;
[Link] = matricNumber;
matricNumber = matricNumber;
ERROR!!!
•this is a special keyword that refers to the current object — the object that is being created or used.
•[Link] → refers to the class field (instance variable)
•studentName → refers to the constructor parameter
CONSTRUCTOR METHOD WITH PARAMETER WITHOUT USING
‘THIS’: EXAMPLE
Use different names for the class field (instance variable) & constructor parameters
DEFAULT CONSTRUCTOR METHOD
• A class may be defined without constructors.
• Java automatically provides a default constructor that initializes all
attributes to their default values.
• This constructor, called a default constructor, is provided
automatically ONLY IF NO constructors are explicitly defined in the
class.
CONSTRUCTOR METHOD: DEFAULT INITIAL VALUES
DEFAULT CONSTRUCTOR METHOD: EXAMPLE
public Student(){
} • There is no constructor
method defined in the
Student class.
123 • Thus, a default constructor
student1 student1 : Student with an empty body is
implicitly included in the class.
123
studName = null
• All attributes will be initialized
matricNumber = null
with appropriate default
marks = 0.0
values. Eg, studentName will
student1 object be initialized to null, while
marks will be 0.0.
NO-ARGUMENT CONSTRUCTOR METHOD
A no-argument constructor public class Student {
is one that you define yourself String studentName;
String matricNum;
with no parameters. double marks;
You can use it to give initial
values manually. // No-argument constructor
public Student() {
studentName = "Undergraduate";
matricNum = “XXXXXX”;
marks = 10;
•Default constructor → created automatically by Java if you }
don’t write one.
•No-argument constructor → written by you, and it can }
assign custom initial values.
ACCESS MODIFIERS
Access Modifiers Description
public The class/attributes/methods can be accessed by the
class/methods of the same class and other classes
private The attributes/methods can ONLY be accessed within
the class where the attributes/methods are defined
Since instance data is private, a class usually provides services to access and modify data
values – through accessor (getter) and mutator (setter) methods.
ACCESSOR(GETTER) & MUTATOR(SETTER) METHODS
▪ To enforce encapsulation, OOP uses accessor and mutator methods in the class.
Accessor
To return the value of a private instance variable.
Also named as getter method.
The method naming scheme: starts with ‘get’ followed by the name of instance variable,
eg: accessor method for ‘studentName’ should be getStudentName()
Mutator
To set the value of a private instance variable.
Also named as setter method.
The method naming scheme: starts with ‘set’ followed by the name of instance variable,
eg: mutator method for ‘studentName’ should be setStudentName()
ACCESSOR(GETTER) METHOD
Instance variables
declared as private
EXAMPLE
OF
ACCESSOR
Public accessor METHODS
methods to access the
private instance
variable
MUTATOR(SETTER) METHOD
(update value of variables)
Instance variables
declared as private
EXAMPLE
OF
Public mutator
MUTATOR
methods to set the
value for private
METHODS
instance variable
toString() METHOD
▪ Is a public value returning method.
▪ A method that returns a String data type.
▪ A method that returns a string which represents the attribute
values for the object.
▪ An alternative for having many accessor method for each
attribute.
EXAMPLE toString() METHOD
public String toString()
{
return "Your name: " +studentName
+"\nYour matric number: " +matricNumber
+"\nYour mark is: " +marks
+"\nYour grade is: " +determineGrade());
}
EXERCISE
You are a new programmer appointed for a mobile phone company. The company requires a new
system to manage mobile phones’ information. Each mobile phone has its model, storage, price
and instalment. Your class should implement the following methods:
1) a constructor to create the object which accepts model,
storage and price as parameters. Object
2) a value returning method named as Attributes
calculateInstalment() which calculate the instalment that
need to be paid by customers. The instalment is Methods
calculated by adding the price with 10% interest, and the UML Diagram
total is divided with the number of months. This method
should accept one parameter which is month. Code
3) a toString() method that returns the attribute values
EXERCISE: ANALYZE THE PROBLEM…
UML CLASS DIAGRAM INPUT, PROSES, OUTPUT
MobilePhone Input: model, storage, price, month
-model: String
-storage: int Process: calculated in calculateInstalment()
-price: double
-instalment: double instalment = ((10.0/100*price)+price)/month;
+ MobilePhone(String model, int storage, double price)
+ calculateInstalment(int month): double
+ toString() : String Output: displayed through toString()