Basic Object Oriented Programming Concept
Basic Object Oriented Programming Concept
Attributes show the state of an object, and represent the characteristics, properties or state that
distinguish classes. The object of a class possesses the data stored in the attribute field or
variable of that class.
Methods on the other hand represent the functions that can be performed by objects. These
methods are defined inside classes and they describe the behaviours of the objects.
From the history of OOP, it was noted that the basis for OOP started in the early 1960s with
Simula 67 as the first programming language to use objects. Smalltalk, developed at the Learning
Research Group at Xerox's Palo Alto Research Center in the early 1970s was taken by many as
first pure object-oriented programming language. In 1982, C++ was implemented after C
programming language with the addition of classes. The design of C++ was done by Bjarne
Stroustrup by combining certain features of Simula with the C programming syntax. Later Java
programming language was modelled after C++ in 1991.
Modularity:
1
Reusability: Code can be reused through inheritance, meaning a team does not
have to write the same code multiple times.
Productivity: Programmers can construct new programs quickly through the use
of multiple libraries and reusable code.
Provides effective means of simulating real- Does not have the means to simulate real-
world event world event effectively
2
Secure because it has proper way of data Less secure because it does not have any
hiding proper way of data hiding
Provide code reusability feature Does not provide code re-usability feature
In this chapter, we are going to look at the basic concepts of object-oriented programming which
include classes, objects, methods instance variables, class declaration, class creation,
constructors, access modifiers, inheritance, homomorphism and data abstraction. The object-
oriented programming approach arranges programs in a real-world object-like form such that
every object is associated with both properties and operations.
Java classes may contain the main method which is the starting point of your program. The main
method is required to execute java program. There are Java classes that do not contain the main
method; such classes are not executable on their own.
For better understanding of these concepts, let us take a simple analogy of using a mobile phone
to make calls. If you want to make a call with your phone, you first press the phone number of
the recipient and press SEND or OK key of the phone. For this to work, the mobile phone will be
built first by the manufacturer. Now, to build the phone requires making an engineering drawing
of the phone description on paper just as house plan is first drawn by a civil engineer. The
engineering drawing on the paper in this analogy represent the class with the description of the
phone. The properties of the phone represent the variable of the class while the tasks that the
phone can perform represent the methods of the class. Since the engineering drawing on the
paper cannot be used to make call, the physical phone has to be constructed following the
specifications in the drawing before you can use it for making calls. This physical phone
constructed represents the object of the class. The alphanumeric keys “hides “the mechanism of
displaying characters on the screen, the OK or SEND key “hide” the mechanism of initiating call
connection to the recipient. This enables users with little or no idea of how phone works to use it
with ease. To make call, pressing the number keys send message to the phone to perform the task
3
of displaying recipient’s phone number on the screen of the phone. Also, pressing the OK or
SEND key sends message to the phone to perform the task of initiating a call. This is the same
way we send message to object of a class through method call and tell the method of the object
to perform a task. The method is the task that is performed when the key is pressed and the
variables are attributes such as the colour, size, shape and different parts of the phone.
We have said that class is a template of an object, therefore, in class declaration; all the features
that object of that class will possess are specified within the class. Every class that starts with
keyword puplic must be stored in a file that has the same name as the class with .java file-name
extension. We will use an example to illustrate how class is declared. Apart from public key
word, class can be specified using other key words like abstract or final or without any modifier
or specifier. . Here is an example of the class for a triangle.
This class declaration begins with keyword public which is an access modifier. We will look at
access modifier in more detail in this section. The access modifier is followed with the keyword
class and then followed by the class’s name. The body of the class is placed within a pair of open
and close braces. The class we declared has two instance variables base and height, both are of
type double and one method with name findArea. The method is declared public indicating that
the method has public access, and has return type double. The open and close bracket that comes
immediately after the method’s name is what shows that it is a method that was declared. Since
4
there is no parameter defined within the open and close bracket, the method is referred to non-
argument method. The body of the method is also delimited in a pair of left and right braces. The
body of the method contains one or more statements that perform the task of the method. In our
example, we have only one statement, return 0.5 * base * height; which returns the area of the
triangle.
Class Triangle
base
height
findArea()
Fifure 1.1 shows diagrammatical description of the Triangle class that was declared above.
With the release of JDK1.1 inner classes features were added. Inner classes are classes declared
inside other classes and as a component of a class can have any accessibility. The scope of inner
class can even be private. You will learn more about class accessibility under access modifier in
this chapter later. The inner class in our example below is called nested and has method
nestedMethod() and data element u. The full name of the nested class is outer.nested. The nested
class has a hidden reference to the outer class instance called this.
5
static method such as the main method, there is no reference to the outer class; hence you must
take special efforts using the new operator and the instance of the outer class.
The Nested class can also be marked static. The keyword static means that the nested class is
associated with the outer class, instead of any particular instance of the outer class. Java allows
programmers to create class within method. It is also possible in Java to create an anonymous
class, which is a class without a specified name.
Anonymous Classes
Anonymous classes are classes created or declared within a method that do not have names. It
removes the burden of thinking of the names to give classes. The objects of such classes cannot
be created or instantiated any other place except where they were declared. The only way you
can instantiate such classes is by using new keyword followed by interface name. An anonymous
class should be made small, if it has more than two methods, it should probably not be declared
anonymous. Anonymous class does not have constructor since it has no specified name to
specify the constructor.
Objects
Objects are creations of classes or instances of classes. All the components of a class (variable
and methods) can only be driven when the object of the class is created. The object is used to
reference or invoke the class elements in order to perform those tasks specified by the class. The
way Java references the class elements is by first creating the object and using the object variable
to reference a particular element of the class.
Object creation
We use class to create object of that class type. However, a two-step process is involved in
creating object of that class type. Initially, you declare a variable of that object which just refers
to the object but does not define it. Thereafter, we obtain the physical copy of the object using
new operator (keyword), followed by the class-name with open and close bracket (default
constructor) and assign it to the variable using an assignment operator (=). These steps can be
performed by the line of code written below.
6
Triangle myTriangle = new Triangle(); This is line of code create a copy of the object of the
triangle class as shown in figure 1.2
Upon the invocation of the new operator, a triangle with the initial values of the base and height
as assigned in the triangle class is created. The object variable could be used to call the findArea
method of the class to return the area of the triangle created. For example:
myTriangle.findArea(); returns the area of the triangle. That is object variable followed by a dot
seperator (.) and the element name.
base
height
findArea()
Triangle t = myTriangle;
Assigning myTriangle to t means that both are referring to the same object and any change made
to the object through t affects the object myTriangle is referring. Even though t and myTriangle
are referring to the same object, they are not linked in any other way. This implies that a
subsequent assignment to t unhook t from the original object without affecting either the object
or myTriangle.
Methods
One of the major constituents of a class is method. Method manipulates the class member
variable. This means that method is declared first inside the class if it is not a method in an
existing java class in the library. Method declaration begins with the method header, followed by
left brace, body of the method and right brace. The general form of a method is as shown below.
7
// body of the method
Return value;
ReturType here specifies the type of data returned which include any of the valid data type.
When a method does not return data, its return type is said to be void. Parameter list is sequence
of type and identifier pair separated by commas. If the method has no parameter, then the
parameter list will be empty. Method that has a return type other than void return a value to the
calling routine as depicted above.
Method overloading occurs when the same method name with different arguments and perhaps
different return type. Imagine a method that calculates the area of a triangle, one such method
may take three of triangle’s sides while another may take three angles of the triangle a length of
one side. In a language that does not support overloading, you would think of having different
method names for a method performing a single action. So, in method overloading, you have a
method that has the same name and return type but the argument list differs either in the order or
type. It is true that overloaded method returns the same result since it performs a single action
with different elements. However, they may also return different result sets in line with their
arguments. Example:
Constructors
Constructors are type of methods that initializes an object immediately upon creation. It is
immediately called once created using the new operator. Constructors have the same name as
that of the class in which they were created inside it. They are different from methods with no
return type, constructors implicitly return the class itself. Finalizers are methods called prior to
garbage collection.
8
Type of Constructor
Default constructor takes no arguments and is created by the complier if no other constructors
are defined in the class. It has public accessibility.
Overloaded constructor takes arguments and is explicitly defined in that class. Example is shown
below:
double a;
int b;
public Myclass(){
Constructors are not inherited into subclasses. You must define each form of constructor that you
need because the component of each class has to be initialized separately. A constructor can
however call the base class constructor using super() mechanism.
Object Oriented Programming languages support at least any of these three principles:
Encapsulation, Inheritance and Polymorphism.
Abstraction
Abstraction is an object-oriented programming principle that allows the showing of important
functionalities to user and the hiding of unwanted information. The unique characteristics of
abstraction is the hiding of unnecessary implementation details from the users. Abstraction
focuses on how to use it and not how it does it.
9
Public class Details
{
Private string name
Private string address
Public void showdetails (string myName, myAddress)
{
name = myName;
address = myAddress;
System.out.println (“the details are +name + “from” + address”);
Int main()
{Detail = new detail(John, No4 Eze Street, Nsukka )
}
}
}
In this example, the variable, name and address are private and as such are not accessible to any
code apart from class detail
Encapsulation
Encapsulation is a concept of object-oriented languages that support the idea of bundling data
and instructions into a variable called an object thereby providing access control to the
information against the outside world. Encapsulation, also called protective wrapper binds both
data and the codes that manipulates them together and at the same time keeps both safe from
outside misuse and interference. A well-defined interface is used for strict control of access to
the bound codes and data. The basis of encapsulation in Java is the class, since when you create a
class; you will specify the code and data that constitute that class. Collectively, these class
elements are called members of the class. Specifically, we refer to data defined by the class as
member variables or instance variables while the codes that manipulate those data are called
member method or just method.
Inheritance
The principle of inheritance provides the ability to enhance or extend the existing objects.
Inheritance is a concept which creates a general class that defines traits common to a set of
related classes and allowing each specific classes to inherit the properties of the general class,
each adding item unique to it. To inherit a class, you simply incorporate the definition of the
superclass (base class) into the derived class (subclass) using extends keyword. Sometimes,
superclass is also called parent class and subclass called child class. Through inheritance, the
object of one class can acquires the properties of the object of another class. This concept of
10
inheritance provides the idea of reusability, which means that additional features can be added to
an existing class without modifying it. The super keyword refers to the superclass of the class in
which super appears. It can be used to invoke the superclass constructor of the superclass
method. The code below illustrates inheritance.
Class Top{
private int x;
public int y;
public int j;
Even though the derived Bottom has been inherited from the base class Top, it is completely
independent and stand-alone class. Moreover, a sub class can also be the base class to other
classes. It is pertinent to note that Java does not support multiple inheritance. This means that a
single class cannot inherit from more than one base or supper class, rather Java supports only
multi-level inheritance. The problem of multiple inheritance is however solved using interface.
Polymorphism
11
but are to share the same external interface. The concept of polymorphism is often expressed by
the phrase “one interface, multiple methods”. With polymorphism, we can design and implement
a general class of operations that may be accessed in the same manner even though the specific
actions associated with each operation may differ. Polymorphism is used in implementing
inheritance. Let’s consider an example of polymorphism implementation.
Class Shape{
Class main{
12
t.draw();
r.draw();
Class Shape{
13
Class main{
t.draw();
r.draw();
In Java, there are three selective control statements or concepts or structure that programmer can
use in writing structured programmers. The selection statement has a boolean expression that
either evaluates as true or false and the result of the evaluation determines the actions to be
performed. Here, we are going to learn about the three types of selection statement available in
Java
If Single-Selection Statement
The if single-selection statement executes an action only when the Boolean expression evaluate
as true and skips execution when the boolean expression evaluates as false. This selection
statement is called If single-selection statement because it selects or skips a single action
depending on the outcome of the of the evaluation of the given boolean expression.
14
If (booleanExpression)
{
Statement(s);
}
From what we have above, if the booleanEpression evaluates as true, the statement or statements
in the block are executed; and skipped, if the booleanEpression evaluate as false.
From the above syntax, the statements within the if block are executed, if the boolean expression
evaluates to true, otherwise, the statements within the else block are executed.
Nested If Statement
If statements or if…else statement can be placed inside another if statement or if…else
statement. When this is done, the inner if statement or if…else statement is said to be nested in
15
the outer one. The inner if statement contain another if statement or if…else statement and this
can occur to any limit. For instance, the following code snippet illustrates nested if statement:
if (j > 0)
{
if (k<0)
cout << “ k is a negative number and j is a positive number’’;
}
cout << “ j may be zero or negative number’’;
Since there is no limit to nesting of if statement, the nested if statement can be used to implement
multiple alternatives.
diagram
Switch Statement
Java provides the switch multiple-selection statement to perform different actions based on the
possible values or expression or integer variable. Each action has a value or a constant integral
expression associated to it. When nested if statement is over used, it make program difficult to
read and to understand. But with switch statement, multiple conditions are efficiently handled.
The switchExpression must yield a value of char, byte, short or int type and must be enclosed in
a bracket.
Syntax for the switch statement
16
Below is the syntax for the switch statement:
switch (switchExpression)
break;
break;
The value1…valueN must have the same data type as the value of the switchExpression. The
statements whose case value matches the value of the switch Expression are executed. Once
executed, the execution of the break statement follows which takes control out of the switch
block. If none of the case value matches the value of the switchExpression, the statements for
default are executed.
Repetitive concept
Repetitive concept or structure also referred to as loop or iteration structure is a structured
programming concept that allows a programmer to specify that a program should repeat an
action as long as some condition remains true. It can also be said that loops are structures that
control repeated executions of block of statements. Java provides three types of repetitive
statements namely; while repetitive statement, do- while repetitive statement, and for repetitive
statement.
17
booleanExpression that controls the actions performed within the loop body. At the end of every
iteration, the loopContinuationCondition is reevaluated. If the result of the reevaluation remains
true, the body of the loop is repeated, otherwise the loop terminates. The syntax for the while
repetitive statement is as follows;
while ( loopContinuationcondition)
{
Statement(s);
}
The part of the loop that contains the statements to be executed is referred to as the loop
body and it is enclosed in curly braces. The curly brace is not compulsory, if the loop
body contains only one statement. The loopContinuationCondition which is a boolean
expression must be enclosed in parenthesis and it is evaluated before the loop body is
executed. Once the condition is no longer true, the loop terminates and program control
transferred to the next statement after the loop.
18
You should remember to enclose the condition in paratheses and terminate it with semicolon;
otherwise error will be triggered during compilation. As it can be seen above, the do-while
repetitive statement executes the loop body first before checking the
loopContinuationCondition to determine whether to continue or not. An example of how do-
while repetitive statement can be used in a program is shown in the program snippet below:
do
{
J = 1;
cout<< j;
j = j+1;
} while (j <= 10);
This code also prints numbers 1 to 10 as long as the condition remains true. The only
different between this code and the one shown on while repetitive statement is that the
number 1 must be printed whether the condition is true or false. This is not the same with
while repetitive because if the initial test fails, no single number will be printed.
The for loop statement begins with the keyword for, followed by initial Action,
loopContinuationCondition, and actionAfterEachIteratinon , all enclose in parentheses, then a
loop body (statements to be executed), which is inside curly braces. The initialAction,
loopContinuationCondition and actionAfterEachIteration which are inside a parenthesis are
separated by semicolons. The for loop uses variable called control variable to control the number
19
of times the loop body is executed. The initial Action initializes the control variable, the
actionAfterEachIteration increments or decrements the control variable, while the
loopContinuationConditin checks whether the control variable has gotten to the final value
(termination value). Example below illustrates how you can use for repetitive statement
For (int k = 0; k < 10; k++)
{
Cout<< “1 am in Java programming class’’;
}
The initialAction (int k = 0) declared and initialized the control variables, k. the control
variable can also be declared outside for loop but it initialization must take place inside the
parenthesis.
The loopContinuationCoddition (K<10) is a booleanExpression and it is evaluated at the
beginning of each iteration. The loop body continues to each time the condition evaluates as true
but terminates and transfers program control to the statement after the loop. The
actionAfterEachIteration (k++) which is the same as k =+ 1 increments the control variable and
forces the loopContinuationCondition to false. If the loop body contains a single statement, the
curly braces can be omitted. You should avoid putting semicolon after for clause to eliminate the
error that goes with such. Hence, the program snippet above will continue to print “I am in
computer programming class” until the loopContinuationCoddition is evaluated to be false.
20