Object Oriented Programing II - Chapter One
Object Oriented Programing II - Chapter One
GENERAL INTRODUCTION
1.1 Software
Computer software, or simply software, also known as computer programs, is the non-
tangible component of computers.
Computer software contrasts with computer hardware, which is the physical component
of computers. Computer hardware and software require each other and neither can be
realistically used without the other.
The word software is the name given to a single program or set of programs.
Application software is the name given to useful program that a user might need
for example, Ms word, spreadsheet.
System software is the name given to special programs that help the computer to
do its job; for example operating systems such as lunix, UNIX, or windows (these
help us to use the computer).
Network software, this helps the computer to communicate with each other
1.2 Evolution of Programming Languages
A program is written by a programmer/developer in a special computer language; these include
C++, C, Java, Basic, FORTRAN and any other.
The compiler translates source code written in high level programming languages into a
machine code.
In case of java byte code, machine code and java byte code consists of binary numbers such as
(0s and 1s) i.e. 01010011 might mean ADD, it is very difficult to write even a short program in
machine language although this is what to be done in the early days of computing, it is because
of this reason that programming language likes java, Visual Basic where developed.
1.2.1 Low level Programming Language
The first and the most basic of the programming language was known as Assembly language, in
this each one of the separate instructions that the computer understands is represented by a word
that bit like an English word; for example MOV for “Move”, JMP for “Jump”, SUB for
“Subtraction” and so on. A special piece of software called an Assembler is then used to turn
those written words into a machine code (Assembler is a low Level language)
Weakness; Some programs require fairly sophisticated instructions for control and data
manipulation, and writing such programs in assembly language is a very tedious business.
1.2.2 High Level Languages
In computing, a programming language designed to suit the requirements of the programmer; it
is independent of the internal machine code of any particular computer. High-level languages
are used to solve problems and are often described as problem-oriented languages; for
example, JAVA, BASIC, COBOL business problems; and FORTRAN is used for programs
solving scientific and mathematical problems.
With the increasing popularity of windows-based systems, the next generation of programming
languages was designed to facilitate the development of GUI interfaces; for example, Visual
Basic wraps the BASIC language in a graphical programming environment. Support for object-
oriented programming has also become more common, for example in C++ and Java. In
contrast, low-level languages, such as assembly languages, closely reflect the machine codes of
specific computers, and are therefore described as machine-oriented languages.
1.3 Common Definitions
A set of instructions into a single statement that you write in a programming language is
called the program code, or source code.
In high level language the translation of the source code to machine code is referred to as
compilation and the software we use to perform this task is termed as the compiler.
The code that is produced by the compiler is often referred to as object code.
The program we write must obey the rules of the programming language. These rules are
known as the syntax (the grammatical structure of a given programming language).
It is very common to make syntax errors when we write a program; programs with
errors (or bugs) in them cannot compile. Some compilers programs when they try to
compile what we have written, also tell us about the errors we have made and where they
are in the program. The process of correcting the errors is referred to as debugging.
These days compilers do much than just compiling programs. They usually provide what
is called an Integrated Development Environment (IDE). This means that the one piece
of software allows us to write programs, compile them to byte code, and also make
changes in response to error messages that are generated by the compiler during
compilation
In Bigger or major projects, different piece of programs are developed separated and need
to be linked or integrated; this process is called linking. An IDE will also perform this
process.
Once a program is compiled and linked is saved as an executable file that can be loaded
into the computer memory (by a special piece of software called loader) and run.
1.4 Java’s Magic: The Byte code
The output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a
highly optimized set of instructions designed to be executed by the Java run-time system,
which is called the Java Virtual Machine (JVM).
JVM was designed as an interpreter for bytecode. The fact that a Java program is
executed by the JVM helps solve the major problems associated with web-based
programs. Here is why.
Translating a Java program into bytecode makes it much easier to run a program in a
wide variety of environments because only the JVM needs to be implemented for each
platform. Once the run-time package exists for a given system, any Java program can run
on it.
If a Java program were compiled to native code, then different versions of the same
program would have to exist for each type of CPU connected to the Internet. This is, of
course, not a feasible solution. Thus, the execution of bytecode by the JVM is the easiest
way to create truly portable programs.
2. An Overview of Java
As in all other computer languages, the elements of Java do not exist in isolation. Rather, they
work together to form the language as a whole. However, this interrelatedness can make it
difficult to describe one aspect of Java without involving several others. Often a discussion of
one feature implies prior knowledge of another. For this reason, this chapter presents a quick
overview of several key features of Java. The material described here will give you a foothold
that will allow you to write and understand simple programs.
What does Object-Oriented Programming (OOP) mean?
Object-oriented programming (OOP) is a software programming model constructed around
objects. This model compartmentalizes data into objects (data fields) and describes object
contents and behavior through the declaration of classes (methods).
Encapsulation
Refers to the creation of self-contained modules that bind processing functions to the
data. These user-defined data types are called classes. Each class contains data as well as
a set of methods which manipulate the data. The data components of a class are called
instance variables and one instance of a class is an object. For example, in a library
system, a class could be member, and John and Sharon could be two instances (two
objects) of the library class.
In Java, the basis of encapsulation is the class. A class defines the structure and behavior
(data and code) that will be shared by a set of objects. Each object of a given class
contains the structure and behavior defined by the class, objects are sometimes referred to
as instances of a class.
When you create a class, you will specify the code and data that constitute that class.
Collectively, these elements are called members of the class. Specifically, the data
defined by the class are referred to as member variables or instance variables. The code
that operates on that data is referred to as member methods or just methods. (in C/C++
programmer calls it a function).
In Java programs, the methods define how the member variables can be used.
Since the purpose of a class is to encapsulate complexity, there are mechanisms for
hiding the complexity of the implementation inside the class. Each method or variable
in a class may be marked private, public or protected.
o The public interface of a class represents everything that external users of the
class need to know, or may know.
o The private methods and data can only be accessed by code that is a member
of the class. Therefore, any other code that is not a member of the class cannot
access a private method or variable.
o The protected methods and data, is accessible in the same classes.
Inheritance
Inheritance is the process by which one object acquires the properties of another
object. This is important because it supports the concept of hierarchical classification.
Without the use of hierarchies, each object would need to define all of its
characteristics explicitly.
However, by use of inheritance, an object need only define those qualities that make
it unique within its class. It can inherit its general attributes from its parent. Thus, it is
the inheritance mechanism that makes it possible for one object to be a specific
instance of a more general case.
Polymorphism
Polymorphism: This means abstract entities are implemented in multiple ways.
Java Program Structure
2.1 A First Simple Program
Now that the basic object-oriented underpinning of Java has been discussed, let’s look at some
actual Java programs.
/*
This is a simple Java program.
*/
C:\>javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version of
the program. As discussed earlier, the Java bytecode is the intermediate representation of
your program that contains instructions the Java Virtual Machine will execute.
To actually run the program, you must use the Java application launcher, called java. To do
so, pass the class name Example as a command-line argument, as shown here:
C:\>java Example
. . .
}
It must be saved in a file called Example.java. Put it in the directory you created
previously.
4. Compile (translate from source code to machine code) by selecting the Tools > Compile
Java menu item. If there are errors go back and forth between the "Command Results"
and the source code by clicking on each of them in the top left pane. Continue with this
process until it compiles correctly.
5. Run the program by choosing Tools > Run Java Application menu item. You will be
using one of these to styles of interaction (Input-Output) at the beginning.
o Console Output (System.out.println(...)). This will open a DOS Command
Window and you will see your text output, followed by "Press any key to
continue . . .".
2.2 A Closer Look at the First Sample Program
Although Example.java is quite short, it includes several key features that are common to all
Java programs. Let’s closely examine each part of the program.
1. The program begins with the following lines:
// Your program begins with a call This is a single-line comment begins with a // and
to main(). ends at the end of the line.
programmers use multiline comments for longer
remarks and single-line comments for brief and
line-by-line descriptions
2. Another line
class Example { This line uses the keyword class to declare that a new class is
being defined (created). Example is an identifier that is the name
of the class. The entire class definition, including all of its
members, will be between the opening curly brace ({) and the
closing curly brace (}).
This line begins the main ( ) method. This is the line at which the program will begin
executing. All Java applications begin execution by calling main( ).
The public keyword is an access specifier, which allows the programmer to control the
visibility of class members. When a class member is preceded by public, then that
member may be accessed by code outside the class in which it is declared.
Methods, members can also be made private, which prevents a member from
being accessed or used by code defined outside of its class.
In this case, main( ) must be declared as public, since it must be called by code
outside of its class when the program is started.
The keyword static allows main ( ) to be called without having to instantiate a particular
instance of the class.
The keyword void simply tells the compiler that main( ) does not return a value. As
you will see later, methods may also return values.
Note:
Java is case-sensitive. Thus, Main is different from main.
It is important to understand that the Java compiler will compile classes that do
not contain a main() method. But java has no way to run these classes.
Any information that you need to pass to a method is received by variables specified
within the set of parentheses that follow the name of the method. These variables are
called parameters. In main( ), there is only one parameter String args[ ]
String args[ ] declares a parameter named args, which is an array of instances of the
class String.(Arrays are collections of similar objects.) Objects of type String store
character strings. In this case, args receives any command-line arguments present when
the program is executed.
public static void main(String args[]) {
The last character on the line is the {. This signals the start of main( )’s body. All of the
code that comprises a method will occur between the method’s opening curly brace and
its closing curly brace}.
2.2.1 println ( ) and print() methods
In the above example the next line of code is shown here. Note that it occurs inside main( ).
This line outputs the string “This is a simple Java program.” followed by a new line on
the screen. Output is actually accomplished by the built-in println( ) method.
println( ) method displays the string, or any other type of information which is passed to
it.
The line begins with System.out.System is a predefined class that provides access to the
system (display monitor), and out is the output stream that is connected to the console.
Notice:
println( ) statement ends with a semicolon. All statements in Java end with a semicolon.
At the end, The first closing braces}in the program ends main( ), and the last } ends the
class definition
The print() method is similar to the println() method, except that it does not break or
advance to the next line. Therefore anything printed after a printstatement will appear on
the same line
Example;
System.out.println ("Liftoff!");
/*
* @author Moses
*/
Best Practices
Don't write comments to document obvious statements.
Every comment has the potential to create an inconsistency between what the comment
says, and what the code does. One cause of "software rot" is that code is changed over
time, but comments are not updated. To avoid this, keep comments next to the code that
is documented so that they may be more easily synchronized.
2.4 Identifiers
Identifiers are used for class names, method names, and variable names.
An identifier maybe any descriptive sequence of uppercase and lowercase letters,
numbers, or the underscore and dollar-sign characters.
They must not begin with a number, lest they be confused with a numeric literal.
Again, Java is case-sensitive, so VALUE is a different identifier than Value.
By convention, programmers use different case styles for different types of identifiers, such as
title case for class names -Lincoln
upper case for constants -MAXIMUM
2.4.1 Variables
A variable is a temporary data storage location in your program. Your code can use one
or many variables, which can contain words, numbers, dates, properties, or object
references.
When a user enters a new value that would be involved in the calculation, to manage that
value, you can (temporarily) store it in the computer memory. Since the values entered in
a reserved memory area change regularly, they are called variables.
You must ask the compiler to reserve an area of memory for a value you intend to use.
Asking the compiler to reserve an area of memory is referred to as Declaring a Variable.
Remember that when you declare a variable, the compiler reserves an area of the
compiler memory for you. Eventually, you can put the desired but appropriate values in
that memory space. Variable Declaration is the process of creating a variable.
To effectively handle this transaction, the compiler would need two pieces of
information from you: a name of your choice for the memory area that will be reserved,
and the type of value that will be stored in that area of memory. Based on this, the
formula to declare a variable is:
TypeOfValue VariableName
Example
int age;
where int is the data type and age is the variable name
As done in some languages like Pascal or Basic, we will start with the name.
2.4.1.1 Guidelines to Naming Variables in Java
When you want the compiler to reserve an area of memory for some values used in your
program, you must set a name, also called an identifier that will allow you to refer to that area of
memory. The name can be anything of your choice but there are rules you must follow:
The name of a variable can be made from letters (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q,
r, s, t, u, v, w, x, y, z, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X,
Y, or Z) only
The name of a variable can start with a letter, an underscore "_", but cannot start with a
digit.
After the first character, the name of the variable can include letters, digits (0, 1, 2, 3, 4,
5, 6, 7, 8, or 9)
The name of a variable cannot be words that the Java language has reserved for its own
use. A reserved word is also called a keyword. This means that you cannot use one of the
following keywords to name your variable:
Beyond these rules as a foundation, Programmers can follow the suggested standards of the Java
naming convention.
A name will start with a letter in lowercase. Examples are age, f4, name, g_14, country
When a name is a combination of words, only the first name will start in lowercase.
Examples are firstName, dateOfBirth, pi_314159
When the name is an abbreviation, we will use uppercase on all characters. Examples are
EAU, UN, MRU, UG
Java is case sensitive:Total, total, andTOTAL are different identifiers
2.4.2 Constants
A constant is an identifier that is similar to a variable except that it holds the same
value during its entire existence. The compiler will issue an error if you try to change
the value of a constant.
In Java, we use the final modifier to declare a constant
Syntax:
final datatype CONSTANTNAME=Value;
Where datatype is the primitive data type, CONSTANTNAME is the name you have
given the constant and value is the value that is to be held constant.
Example
final int MIN_HEIGHT = 69;
2.4.2.1 Advantages of using Constants
They give meaning to otherwise unclear literal values –Example: MAX_LOAD means
more than the literal 250
They facilitate program maintenance –If a constant is used in multiple places, its value
need only be set in one place
They formally establish that a value should not change, avoiding inadvertent errors by
other programmers
2.4.3 The Scope and Lifetime of Variables
Many other computer languages define two general categories of scopes: global and local.
return miles;
NOTE:
Visibility: Only in defining method. No code outside a method can see the local
variables inside another method. There is no need, or even possibility, of declaring a
local variable with a visibility modifier -- local variables are automatically known
only in the method itself.
Initial value: None. Local variables don't have initial values by default -- you can't
try to use their value until you assign a value. It's therefore common to assignment a
value to them when they're declared.