Java OOP Basics and Benefits Explained
Java OOP Basics and Benefits Explained
| HOME
Why re-invent the wheels? Why re-writing codes? Can you write better codes than those codes written by the experts?
The task force proposed to make software behave like hardware OBJECT. Subsequently, DoD replaces over 450 computer
languages, which were then used to build DoD systems, with an object-oriented language called Ada.
Most importantly, some of these classes (such as Ball and Audience) can be reused in another application, e.g., computer basketball
game, with little or no modification.
Benefits of OOP
The procedural-oriented languages focus on procedures, with function as the basic unit. You need to first figure out all the functions and
then think about how to represent data.
The object-oriented languages focus on components that the user perceives, with objects as the basic unit. You figure out all the objects
by putting all the data and operations that describe the user's interaction with the data.
2. OOP in Java
An instance is a realization of a particular item of a class. In other words, an instance is an instantiation of a class. All the instances of a
class have similar properties, as described in the class definition. For example, you can define a class called "Student" and create three
instances of the class "Student" for "Alice", "Ah Beng" and "Ali".
The term "object" usually refers to instance. But it is often used loosely, and may refer to a class or an instance.
In other words, a class encapsulates the static attributes (data) and dynamic behaviors
(operations that operate on the data) in a box.
The following figure shows two instances of the class Student, identified as "paul" and "peter".
Unified Modeling Language (UML) Class and Instance Diagrams: The above class diagrams are drawn according to the
UML notations. A class is represented as a 3-compartment box, containing name, variables, and methods, respectively. Class name is
shown in bold and centralized. An instance is also represented as a 3-compartment box, with instance name shown as
instanceName:Classname and underlined.
Brief Summar y
1. A class is a programmer-defined, abstract, self-contained, reusable software entity that mimics a real-world thing.
2. A class is a 3-compartment box containing the name, variables and the methods.
3. A class encapsulates the data structures (in variables) and algorithms (in methods). The values of the variables constitute its state.
The methods constitute its behaviors.
4. An instance is an instantiation (or realization) of a particular item of a class.
We shall explain the access control modifier, such as public and private, later.
Class Naming Convention: A class name shall be a noun or a noun phrase made up of several words. All the words shall be initial-
capitalized (camel-case). Use a singular noun for class name. Choose a meaningful and self-descriptive classname. For examples,
SoccerPlayer, HttpProxyServer, FileInputStream, PrintStream and SocketFactory.
For examples, suppose that we have a class called Circle, we can create instances of Circle as follows:
When an instance is declared but not constructed, it holds a special value called null.
For example,
// Suppose that the class Circle has variables radius and color,
// and methods getArea() and getRadius().
// Declare and construct instances c1 and c2 of the class Circle
Circle c1 = new Circle ();
Circle c2 = new Circle ();
// Invoke member methods for the instance c1 via dot operator
[Link]([Link]());
[Link]([Link]());
// Reference member variables for instance c2 via dot operator
[Link] = 5.0;
[Link] = "blue";
Calling getArea() without identifying the instance is meaningless, as the radius is unknown (there could be many instances of Circle -
each maintaining its own radius). Furthermore, [Link]() and [Link]() are likely to produce different results.
In general, suppose there is a class called AClass with a member variable called aVariable and a member method called aMethod(). An
instance called anInstance is constructed for AClass. You use [Link] and [Link]().
Variable Naming Convention: A variable name shall be a noun or a noun phrase made up of several words. The first word is in
lowercase and the rest of the words are initial-capitalized (camel-case), e.g., fontSize, roomNumber, xMax, yMin and xTopLeft.
For example,
For examples:
Method Naming Convention: A method name shall be a verb, or a verb phrase made up of several words. The first word is in
lowercase and the rest of the words are initial-capitalized (camel-case). For example, getArea(), setRadius(), getParameterValues(),
hasNext().
Variable name vs. Method name vs. Class name : A variable name is a noun, denoting an attribute; while a method name is a
verb, denoting an action. They have the same naming convention (the first word in lowercase and the rest are initial-capitalized).
Nevertheless, you can easily distinguish them from the context. Methods take arguments in parentheses (possibly zero arguments with
empty parentheses), but variables do not. In this writing, methods are denoted with a pair of parentheses, e.g., println(), getArea() for
clarity.
On the other hand, class name is a noun beginning with uppercase.
A class called Circle is defined as shown in the class diagram. It contains two private member variables: radius (of type double) and
color (of type String); and three public member methods: getRadius(), getColor(), and getArea().
Three instances of Circles, called c1, c2, and c3, shall be constructed with their respective data members, as shown in the instance
diagrams.
[Link]
1 /**
2 * The Circle class models a circle with a radius and color.
3 */
4 public class Circle { // Save as "[Link]"
5 // Private instance variables
6 private double radius;
7 private String color;
8
9 // Constructors (overloaded)
10 /** Constructs a Circle instance with default radius and color */
11 public Circle() { // 1st Constructor (default constructor)
12 radius = 1.0;
13 color = "red";
14 }
15 /** Constructs a Circle instance with the given radius and default color*/
16 public Circle(double r) { // 2nd Constructor
17 radius = r;
18 color = "red";
19 }
20 /** Constructs a Circle instance with the given radius and color */
21 public Circle(double r, String c) { // 3rd Constructor
22 radius = r;
23 color = c;
24 }
25
26 // Public methods
27 /** Returns the radius */
28 public double getRadius() { // getter for radius
29 return radius;
30 }
31 /** Returns the color */
32 public String getColor() { // getter for color
33 return color;
34 }
35 /** Returns the area of this circle */
36 public double getArea() {
37 return radius * radius * [Link];
38 }
39 }
cd \path\to\project-directory
javac [Link]
Notice that the Circle class does not have a main() method. Hence, it is NOT a standalone program and you cannot run the Circle
class by itself. The Circle class is meant to be a building block - to be used in other programs.
[Link]
We shall now write another class called TestCircle, which uses the Circle class. The TestCircle class has a main() method and can
be executed.
1 /**
2 * A Test Driver for the "Circle" class
3 */
4 public class TestCircle { // Save as "[Link]"
5 public static void main(String[] args) { // Program entry point
6 // Declare and Construct an instance of the Circle class called c1
7 Circle c1 = new Circle(2.0, "blue"); // Use 3rd constructor
8 [Link]("The radius is: " + [Link]()); // use dot operator to invoke member methods
9 //The radius is: 2.0
10 [Link]("The color is: " + [Link]());
11 //The color is: blue
12 [Link]("The area is: %.2f%n", [Link]());
13 //The area is: 12.57
14
15 // Declare and Construct another instance of the Circle class called c2
16 Circle c2 = new Circle(2.0); // Use 2nd constructor
17 [Link]("The radius is: " + [Link]());
18 //The radius is: 2.0
19 [Link]("The color is: " + [Link]());
20 //The color is: red
21 [Link]("The area is: %.2f%n", [Link]());
22 //The area is: 12.57
23
24 // Declare and Construct yet another instance of the Circle class called c3
25 Circle c3 = new Circle(); // Use 1st constructor
26 [Link]("The radius is: " + [Link]());
27 //The radius is: 1.0
28 [Link]("The color is: " + [Link]());
29 //The color is: red
30 [Link]("The area is: %.2f%n", [Link]());
31 //The area is: 3.14
32 }
33 }
javac [Link]
java TestCircle
2.9 Constructors
A constructor is a special method that has the same method name as the class name. That is, the constructor of the class Circle is called
Circle(). In the above Circle class, we define three overloaded versions of constructor Circle(...). A constructor is used to construct
and initialize all the member variables. To construct a new instance of a class, you need to use a special "new" operator followed by a call
to one of the constructors. For example,
Circle c1 = new Circle(); // use 1st constructor
Circle c2 = new Circle(2.0); // use 2nd constructor
Circle c3 = new Circle(3.0, "red"); // use 3rd constructor
Default Constructor : A constructor with no parameter is called the default constructor. It initializes the member variables to their
default values. For example, the Circle() in the above example initialize member variables radius and color to their default values.
Example: The method average() has 3 versions, with different parameter lists. The caller can invoke the chosen version by supplying
the matching arguments.
1 /**
2 * Example to illustrate "Method Overloading"
3 */
4 public class MethodOverloadingTest {
5 public static int average(int n1, int n2) { // version 1
6 [Link]("Run version 1");
7 return (n1+n2)/2;
8 }
9 public static double average(double n1, double n2) { // version 2
10 [Link]("Run version 2");
11 return (n1+n2)/2;
12 }
13 public static int average(int n1, int n2, int n3) { // version 3
14 [Link]("Run version 3");
15 return (n1+n2+n3)/3;
16 }
17
18 public static void main(String[] args) {
19 [Link](average(1, 2));
20 //Run version 1
21 //1
22 [Link](average(1.0, 2.0));
23 //Run version 2
24 //1.5
25 [Link](average(1, 2, 3));
26 //Run version 3
27 //2
28 [Link](average(1.0, 2));
29 //Run version 2 (int 2 implicitly casted to double 2.0)
30 //1.5
31
32 //average(1, 2, 3, 4);
33 //compilation error: no suitable method found for average(int,int,int,int)
34 }
35 }
Note : C language does not support method overloading. You need to use different method names for each of the variations. C++, Java,
C# support method overloading.
For example, in the above Circle definition, the member variable radius is declared private. As the result, radius is accessible inside
the Circle class, but NOT in the TestCircle class. In other words, you cannot use "[Link]" to refer to c1's radius in TestCircle.
Try inserting the statement "[Link]([Link])" in TestCircle and observe the error message (error: radius has
private access in Circle).
Try changing radius to public in the Circle class, and re-run the above statement.
On the other hand, the method getRadius() is declared public in the Circle class. Hence, it can be invoked in the TestCircle class,
e.g., [Link]().
UML Notation: In UML class diagram, public members are denoted with a "+"; while private members with a "-".
Member variables of a class are typically hidden from the outside word (i.e., the other classes), with private access control modifier.
Access to the member variables are provided via public assessor methods, e.g., getRadius() and getColor().
This follows the principle of information hiding. That is, objects communicate with each others using well-defined interfaces (public
methods). Objects are not allowed to know the implementation details of others. The implementation details are hidden or encapsulated
within the class. Information hiding facilitates reuse of the class.
Rule of Thumb: Do not make any variables public, unless you have a good reason.
To allow other classes to modify the value of a private variable say xxx, we provide a set method (or setter or mutator method) called
setXxx(). A set method could provide data validation (such as range checking), or transform the raw data into the internal
representation.
For example, in our Circle class, the variables radius and color are declared private. That is to say, they are only accessible within the
Circle class and not visible in any other classes, including the TestCircle class. You cannot access the private variables radius and
color from the TestCircle class directly - via say [Link] or [Link]. The Circle class provides two public accessor methods,
namely, getRadius() and getColor(). These methods are declared public. The class TestCircle can invoke these public accessor
methods to retrieve the radius and color of a Circle object, via say [Link]() and [Link]().
There is no way you can change the radius or color of a Circle object, after it is constructed in the TestCircle class. You cannot issue
statements such as [Link] = 5.0 to change the radius of instance c1, as radius is declared as private in the Circle class and is
not visible to other classes including TestCircle.
If the designer of the Circle class permits the change the radius and color after a Circle object is constructed, he has to provide the
appropriate set methods (or setters or mutator methods), e.g.,
// Setter for color
public void setColor(String newColor) {
color = newColor;
}
With proper implementation of information hiding, the designer of a class has full control of what the user of the class can and cannot do.
In the above codes, there are two identifiers called radius - a member variable of the class and the method's parameter. This causes
naming conflict. To avoid the naming conflict, you could name the method's argument r instead of radius. However, radius is more
approximate and meaningful in this context. Java provides a keyword called this to resolve this naming conflict. "[Link]" refers to
the member variable; while "radius" resolves to the method's argument.
Using the keyword "this", the constructor, getter and setter methods for a private variable called xxx of type T are as follows:
// Constructor
public Ccc(T xxx) {
[Link] = xxx;
}
// A getter for variable xxx of type T receives no argument and return a value of type T
public T getXxx() {
return xxx; // or "return [Link]" for clarity
}
// A setter for variable xxx of type T receives a parameter of type T and return void
public void setXxx(T xxx) {
[Link] = xxx;
}
}
For a boolean variable xxx, the getter shall be named isXxx() or hasXxx(), which is more meaningful than getXxx(). The setter
remains as setXxx().
// getter
public boolean isXxx() {
return xxx; // or "return [Link]" for clarity
}
// setter
public void setXxx(boolean xxx) {
[Link] = xxx;
}
More on "this"
[Link] refers to varName of this instance; [Link](...) invokes methodName(...) of this instance.
In a constructor, we can use this(...) to call another constructor of this class.
Inside a method, we can use the statement "return this" to return this instance to the caller.
For example, include the following toString() method in our Circle class:
In your TestCircle class, you can get a description of a Circle instance via:
Constant Naming Convention: A constant name is a noun, or a noun phrase made up of several words. All words are in uppercase
separated by underscores '_', for examples, X_REFERENCE, MAX_INTEGER and MIN_VALUE.
Write the Date class and a test driver to test all the public methods. No Input validations are required for day, month, and year.
/** Constructs a Date instance with the given year, month and day. No input validation */
public Date(int year, int month, int day) {
[Link] = year;
[Link] = month;
[Link] = day;
}
// Test setDate()
[Link](2988, 1, 2);
[Link](d1);
//01/02/2988
}
}
A class called Time, which models a time instance with hour, minute and second, is designed as shown in the class diagram. It contains the
following members:
3 private instance variables hour, minute, and second.
Constructors, getters and setters.
A method setTime() to set hour, minute and second.
A toString() that returns "hh:mm:ss" with leading zero if applicable.
A method nextSecond() that advances this instance by one second. It returns this instance to support chaining (cascading)
operations, e.g., [Link]().nextSecond(). Take note that the nextSecond() of 23:59:59 is 00:00:00.
Write the Time class and a test driver to test all the public methods. No input validations are required.
/** Returns a self-descriptive string in the form of "hh:mm:ss" with leading zeros */
public String toString() {
// Use built-in function [Link]() to form a formatted String
return [Link]("%02d:%02d:%02d", hour, minute, second);
// Specifier "0" to print leading zeros, if available.
}
/** Advances this Time instance by one second, and returns this instance to support chaining */
public Time nextSecond() {
++second;
if (second >= 60) {
second = 0;
++minute;
if (minute >= 60) {
minute = 0;
++hour;
if (hour >= 24) {
hour = 0;
}
}
}
return this; // Return "this" instance, to support chaining operations
// e.g., [Link]().nextSecond()
}
}
A Test Driver ([Link])
/**
* A Test Driver for the Time class
*/
public class TestTime {
public static void main(String[] args) {
// Test Constructors and toString()
Time t1 = new Time(1, 2, 3);
[Link](t1); // toString()
//03:02:01
Time t2 = new Time(); // The default constructor
[Link](t2);
//00:00:00
// Test setTime()
[Link](58, 59, 23);
[Link](t1);
//23:59:58
A Point class models a 2D point at (x,y), as shown in the class diagram. It contains the following members:
2 private instance variables x and y, which maintain the location of the point.
Constructors, getters and setters.
A method setXY(), which sets the x and y of the point; and a method getXY(), which returns the x and y in a 2-element int array.
A toString(), which returns "(x,y)".
/** Return the distance from this instance to the given point at (x,y). Invoke via [Link](1,2) */
public double distance(int x, int y) {
int xDiff = this.x - x;
int yDiff = this.y - y;
return [Link](xDiff*xDiff + yDiff*yDiff);
}
/** Returns the distance from this instance to the given Point instance. Invoke via [Link](p2) */
public double distance(Point another) {
int xDiff = this.x - another.x;
int yDiff = this.y - another.y;
return [Link](xDiff*xDiff + yDiff*yDiff);
}
/** Returns the distance from this instance to (0,0). Invoke via [Link]() */
public double distance() {
return [Link](this.x*this.x + this.y*this.y);
}
}
/**
* The Time class models a time instance with second, minute and hour.
* This class performs input validations.
*/
public class Time {
// The private instance variables - with input validations.
private int second; // valid range is [0, 59]
private int minute; // valid range is [0, 59]
private int hour; // valid range is [0, 23]
/** Sets second, minute and hour to the given values with input validation */
public void setTime(int second, int minute, int hour) {
// Invoke setters to do input validation
[Link](second);
[Link](minute);
[Link](hour);
}
/** Constructs a Time instance with the given values with input validation */
public Time(int second, int minute, int hour) {
// Invoke setters to do input validation
[Link](second, minute, hour);
}
/** Constructs a Time instance with default values */
public Time() { // The default constructor
[Link] = 0;
[Link] = 0;
[Link] = 0;
}
/** Returns a self-descriptive string in the form of "hh:mm:ss" with leading zeros */
public String toString() {
return [Link]("%02d:%02d:%02d", hour, minute, second);
}
/** Advances this Time instance by one second and returns this instance to support chaining */
public Time nextSecond() {
++second;
if (second == 60) { // We are sure that second <= 60 here because of the input validation
second = 0;
++minute;
if (minute == 60) {
minute = 0;
++hour;
if (hour == 24) {
hour = 0;
}
}
}
return this; // Return this instance, to support chaining
}
}
Exercise : Write a Test Driver to test the above Time class with various valid and invalid values.
3.5 EG. 5 (Advanced): The Time Class with Input Validation via Exception Handling
In the previous example, we print a error message and set the variable to 0, if the input is invalid. This is less than perfect. The proper way
to handle invalid inputs is via the so-called exception handling mechanism.
1 /**
2 * The Time class models a time instance with second, minute and hour.
3 * This class performs input validations using exception handling.
4 */
5 public class Time {
6 // The private instance variables - with input validations.
7 private int second; // valid range is [0, 59]
8 private int minute; // valid range is [0, 59]
9 private int hour; // valid range is [0, 23]
10
11 // Input validations are done in the setters.
12 // All the other methods (such as constructors and setTime()) invoke
13 // these setters to perform input validations to avoid code duplication.
14 /** Sets the second to the given value with input validation */
15 public void setSecond(int second) {
16 if (second >=0 && second <= 59) {
17 [Link] = second;
18 } else {
19 throw new IllegalArgumentException("invalid second");
20 }
21 }
22 /** Sets the minute to the given value with input validation */
23 public void setMinute(int minute) {
24 if (minute >=0 && minute <= 59) {
25 [Link] = minute;
26 } else {
27 throw new IllegalArgumentException("invalid minute");
28 }
29 }
30 /** Sets the hour to the given value with input validation */
31 public void setHour(int hour) {
32 if (hour >=0 && hour <= 23) {
33 [Link] = hour;
34 } else {
35 throw new IllegalArgumentException("invalid hour");
36 }
37 }
38
39 /** Sets second, minute and hour to the given values with input validation */
40 public void setTime(int second, int minute, int hour) {
41 // Invoke setters to do input validation
42 [Link](second);
43 [Link](minute);
44 [Link](hour);
45 }
46
47 /** Constructs a Time instance with the given values with input validation */
48 public Time(int second, int minute, int hour) {
49 // Invoke setters to do input validation
50 [Link](second, minute, hour);
51 }
52 /** Constructs a Time instance with default values */
53 public Time() { // The default constructor
54 [Link] = 0;
55 [Link] = 0;
56 [Link] = 0;
57 }
58
59 // The public getters
60 /** Returns the second */
61 public int getSecond() {
62 return [Link];
63 }
64 /** Returns the minute */
65 public int getMinute() {
66 return [Link];
67 }
68 /** Returns the hour */
69 public int getHour() {
70 return [Link];
71 }
72
73 /** Returns a self-descriptive string in the form of "hh:mm:ss" with leading zeros */
74 public String toString() {
75 return [Link]("%02d:%02d:%02d", hour, minute, second);
76 }
77 /** Advances this Time instance by one second and returns this instance to support chaining */
78 public Time nextSecond() {
79 ++second;
80 if (second == 60) { // We are sure that second <= 60 here because of the input validation
81 second = 0;
82 ++minute;
83 if (minute == 60) {
84 minute = 0;
85 ++hour;
86 if (hour == 24) {
87 hour = 0;
88 }
89 }
90 }
91 return this; // Return this instance, to support chaining
92 }
93 }
Exception Handling
What to do if an invalid hour, minute or second was given as input argument? Print an error message? Terminate the program abruptly?
Continue operation by setting the parameter to its default? This is a really hard decision and there is no perfect solution that suits all
situations.
In Java, instead of printing an error message, you can throw an so-called Exception object (such as IllegalArgumentException) to the
caller, and let the caller handles the exception gracefully.
If the caller provides an invalid hour without handling the exception, the program terminates with a runtime error. For example,
The caller can choose to handle the exception using the try-catch construct to process the exception gracefully. For example,
/**
* A Test Driver for the Time class
*/
public class TestTime {
public static void main(String[] args) {
// Case 1: valid input
//int hour = 23, minute = 58, second = 58;
// Case 2: invalid input
int hour = 24, minute = 58, second = 58;
Time t12;
try {
t12 = new Time(second, minute, hour);
// If input is invalid, throw exception. Skip the rest, goto "catch".
// Else complete "try", skip "catch"
[Link]("valid input");
} catch (IllegalArgumentException ex) {
// You have the opportunity to do something to recover from the error.
[Link](); // print error messages
[Link]("Error in input. Set to default value");
// You should ask the user to provide the valid input instead!
t12 = new Time();
}
// Case 1 output
//valid input
//Time is 23:58:58
//Life goes on...
// Case 2 output
//[Link]: invalid hour
//Error in input. Set to default value
//Time is 00:00:00
//Life goes on...
}
}
The statements in the try-clause will be executed. If all the statements in the try-clause are successful, the catch-clause is ignored, and
execution continues to the next statement after try-catch. However, if one of the statement in the try-clause throws an exception (in
this case, an IllegalArgumentException), the rest of try-clause will be skipped, and the execution will be transferred to the catch-
clause. The program always continues to the next statement after the try-catch (instead of abruptly terminated).
A class called Account, which models a bank account, is designed as shown in the class diagram. It contains the following members:
Two private instance variables: accountNumber (int), and balance (double) which maintains the current account balance.
Constructors (overloaded).
Getters and Setters for the private instance variables. There is no setter for accountNumber as it is not designed to be changed.
public methods credit() and debit(), which adds/subtracts the given amount to/from the balance, respectively.
A toString(), which returns "A/C no:xxx, Balance=$[Link]", with balance rounded to two decimal places.
Write the Account class and a test driver to test all the public methods.
[Link](1.0, a1);
[Link](a1);
//Account[number=5566,balance=$6.60]
[Link](a2);
//Account[number=1234,balance=$98.90]
}
}
Tr y : Re-design the methods credit(), debit() and transferTo() to return this instance, so that these methods can be chained, e.g.,
[Link](10).credit(20).debit(5).transferTo(5.5, a2). For debit() and transferTo() you need to throw an exception
instead printing an error message. See the above Time class.
A Ball class models a moving ball, is designed as shown in the class diagram. It contains the following members:
4 private variables x, y, xStep, yStep, which maintain the position of the ball and the displacement per move step.
Constructors, getters and setters.
Method setXY() and setXYStep(), which sets the position and step size of the ball; and getXY() and getXYSpeed().
A toString(), which returns "Ball@(x,y),speed=(xStep,yStep)".
A method move(), which increases x and y by xStep and yStep respectively; and returns this instance to support chaining
operation.
We can design the Student class as shown in the class diagram. It contains the following members:
private instance variables name (String), address (String), numCourses (int), course (String[30]) and grades (int[30]). The
numCourses keeps track of the number of courses taken by this student so far. The courses and grades are two parallel arrays,
storing the courses taken (e.g., {"IM101", "IM102", "IM103"}) and their respective grades (e.g. {89, 56, 98}).
A constructor that constructs an instance with the given name and Address. It also constructs the courses and grades arrays and set
the numCourses to 0.
Getters for name and address; setter for address. No setter is defined for name as it is not designed to be changed.
A method getAverageGrade(), which returns the average grade of all the courses taken.
3.9 Exercises
LINK TO EXERCISES
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@[Link]) | HOME