Professional Documents
Culture Documents
Chapter One
Introduction to Object-Oriented Programming
1.1. Types of Programming Paradigm
Programming
In computer science fields, the word program characterizes what a computer actually does and this process is
known as programming. Programming is the process that models or structure the set of instructions that
instruct the machine how to perform a task and what to perform. It can be done using a variety of
programming languages such as C, C++, C#, Python, Java, etc.
Programming Paradigms
When programming, complexity is always the enemy. Programs with great complexity, with many moving
parts and interdependent components, seem initially impressive. However, the ability to translate a real-world
problem into a simple or elegant solution requires a deeper understanding. While developing an application or
solving a simple problem, we often say “If I had more time, I would have written a simpler program”. The
reason is, we made a program with greater complexity. The less complexity we have, the easier it is to debug
and understand. The more complex a program becomes, the harder it is to work on it. Managing complexity
is a programmer’s main concern. There are many general approaches that reduce complexity in a program
or make it more manageable. One of the main approaches is a programming paradigm.
A programming paradigm is a style, or “way,” of programming. It does not refer to a specific language, but
rather it refers to the way you program. Programming paradigms are a way to classify programming languages
based on their features. Some languages make it easy to write in some paradigms but not others. In the context
of programming language, it refers to a set of design principles that defines the program structure.
Programming paradigm is a way to deal with tackle issues utilizing some programming language.
It differs in the concepts and methods that are used to represent the elements (such as objects, variables,
functions, and constraints) of a program. The steps that involve a calculation (like assignations, evaluation,
continuations, and data flows). The lowest programming paradigm is machine code.
There are lots of things for programming languages that are known. However, every one of them needs to
follow some procedure when they are executed and this approach/methodology is a paradigm.
1|Page
Object Oriented Programming in Java Lecture note
The execution of the program statements is decided by the control flow statements. And the program flow can
be directed as per the program logic.
Examples: C, FORTRAN, Basic, Java, C++, Python, Ruby, PHP, etc.
2. Procedural Programming
This paradigm consists of set of procedures which is referred as function, method or subroutines. Each
function performs specific operation. The function consists of group of computational steps that directs the
computer to perform specific operation. The function once defined can be called many times in the program to
repeat the same operation. The programmer can either use standard library functions or create library of user-
defined functions.
Examples: FORTRAN C,
C++, Java, Ruby, PHP,
JavaScript, Python, Pascal,
ColdFusion and COBOL.
2|Page
Object Oriented Programming in Java Lecture note
3|Page
Object Oriented Programming in Java Lecture note
2. Logical Programming
This declarative programming paradigm that is based on the logic and control. The term logic means
essentially facts and rules. Whereas control means, an order of rules. The term algorithm is defined as logic
plus control (Logic + Control). The logic defines what should be solved and the control defines how it should
be solved.
The program written in logic programming language consists of set of program statements in the logical form.
Each statement is an expression of facts, rules and order of rules. The logic programming is an abstract model
of computation. It is based on the first order predicate logic (FOL).
A logical program is divided into three sections:
1. a series of definitions/declarations that define the problem domain
2. statements of relevant facts
3. statement of goals in the form of a query
Example of Logic programming is Prolog, F-Logic and etc.
Multi-Paradigm
The programming languages that support more than one programming paradigm fall into this category. The
design goal of such languages is to allow programmers to use the most suitable programming style associated
with languages constructs for a given job.
The example of multi-paradigm programming languages is C++, Java, Python, etc. The languages support
object-oriented programming greater or lesser degree, typically in combination with imperative and
declarative programming paradigm.
Usually, in a program, distinctive programming standards are utilized. Henceforth, programming dialects
offer help (with various degrees) for the different standards.
4|Page
Object Oriented Programming in Java Lecture note
5|Page
Object Oriented Programming in Java Lecture note
In the above diagram, the object ‘Dog’ has both state and behavior. An object stores its information in
attributes and discloses its behavior through methods in Java program.
6|Page
Object Oriented Programming in Java Lecture note
Class
Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint from which
you can create an individual object. Class doesn't consume any memory space.
Example, if you had a class called “Car” it could have objects like Mercedes, BMW, Toyota, etc. Its
properties (data) can be price or speed of these cars. While the methods may be performed with these cars are
driving, reverse, braking etc.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a
capsule, it is wrapped with different medicines. A java class is the example of encapsulation. Java bean is the
fully encapsulated class because all the data members are private here.
7|Page
Object Oriented Programming in Java Lecture note
programming language was originally developed by Sun Microsystems which was initiated by James Gosling
and released in 1995 as core component of Sun Microsystems’ Java platform (Java 1.0 [J2SE]). Sun
Microsystems in 1991 funded an internal corporate research project led by James Gosling, which resulted in
a C++-based object-oriented programming language Sun called Java. As of December 2008, the latest release
of the Java Standard Edition is 6 (J2SE). With the advancement of Java and its widespread popularity,
multiple configurations were built to suite various types of platforms. Ex: J2EE for Enterprise Applications,
J2ME for Mobile Applications. Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and
Java ME, respectively. A key goal of Java is to be able to write programs that will run on a great variety of
computer systems and computer-control devices. This is sometimes called “write once, run anywhere.” Java is
guaranteed to be Write Once, Run Anywhere.
8|Page
Object Oriented Programming in Java Lecture note
performance clients and a modern look-and-feel as well as high-level APIs for connecting to networked
data sources. JavaFX applications may be clients of Java EE platform services.
1. Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
2. Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.
3. Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an enterprise
application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used for
creating enterprise applications.
4. Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and Java
ME are used for creating mobile applications.
Features of Java
Programmers have accepted java very quickly because it provides everything that is needed in a modern-day
language including the following features.
Java is:
❖ Object Oriented – In Java, everything is an Object. Java can be easily extended since it is based on
the Object model.
❖ Platform Independent – Unlike many other programming languages including C and C++, when
Java is compiled, it is not compiled into platform specific machine, rather into platform-independent
byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on. Platform-independence is a program’s capability of moving
easily from one computer system to another. A platform is the hardware or software environment in
9|Page
Object Oriented Programming in Java Lecture note
which a program runs. There are two types of platforms software-based and hardware-based. Java
provides a software-based platform.
❖ Simple – Java is designed to be easy to learn and understand, and its syntax is simple. If you understand
the basic concept of OOP Java, it would be easy to master. According to Sun, Java language is a simple
programming language because:
o Java syntax is based on C++.
o Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
❖ Secure – With Java’s secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption. Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
❖ Class loader – it is part of the Java Runtime Environment (JRE) which is used to load Java classes into
the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
o Bytecode Verifier – it checks the code fragments for illegal code that can violate access right to
objects.
o Security Manager – it determines what resources a class can access such as reading and writing
to the local disk.
❖ Architecture-neutral – Java compiler generates an architecture-neutral object file format, which makes
the compiled code executable on many processors, with the presence of Java runtime system and the
size of primitive types is fixed. In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for
both 32 and 64-bit architectures in Java.
❖ Portable – Being architecture-neutral and having no implementation dependent aspects of the
specification makes Java portable. Java Byte code can be carried to any platform. No implementation-
10 | P a g e
Object Oriented Programming in Java Lecture note
dependent features. Everything related to storage is predefined, for example, the size of primitive data
types.
❖ Robust – Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile
time error checking and runtime checking. Robust simply means strong.
Java is robust because:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points make
Java robust.
❖ Multithreaded – With Java’s multithreaded feature it is possible to write programs that can perform
many tasks simultaneously. This design feature allows the developers to construct interactive
applications that can run smoothly. A thread is like a separate program, executing concurrently. We can
write Java programs that deal with many tasks at once by defining multiple threads. It shares a common
memory area.
❖ Interpreted – Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an incremental and
light-weight process.
❖ High Performance – With the use of Just-In-Time compilers, Java enables high performance. Java is
faster than other traditional interpreted programming languages because Java bytecode is “close” to
native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted
language that is why it is slower than compiled languages, e.g., C, C++, etc.
❖ Distributed – Java is designed for the distributed environment of the internet. Java is distributed
because it facilitates users to create distributed applications in Java. This feature of Java makes us able
to access files by calling the methods from any machine on the internet.
❖ Dynamic – Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Java programs can carry an extensive amount of run-time information that can be
used to verify and resolve accesses to objects at run-time. It supports dynamic loading of classes. It
means classes are loaded on demand. It also supports functions from its native languages, i.e., C and
C++.
11 | P a g e
Object Oriented Programming in Java Lecture note
• Java Editor – You can use any text editor or IDE to create and edit a Java source-code file.
• Java Development Toolkit (JDK) – it consists of a set of separate programs, each invoked from a
command line, for developing and testing Java programs. Besides JDK, you can use a Java
development tool (e.g., NetBeans, Eclipse, and TextPad). It contains a private Java Virtual Machine
(JVM) and a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver
(jar), a documentation generator (Javadoc), etc. to complete the development of a Java Application.
• Integrated Development Environment (IDE) – it provides tools that support the software development
process, including editors for writing and editing programs and debuggers for locating logic errors (errors
that cause programs to execute incorrectly). Popular IDEs include Eclipse (www.eclipse.org)
and NetBeans (www.netbeans.org).
• Application Programming Interface (API) – contains predefined classes and interfaces for developing
Java programs.
• Java Runtime Environment (JRE) – it is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically
exists. It contains a set of libraries + other files that JVM uses at runtime.
• Java Virtual Machine (JVM) – is an abstract machine. It is called a virtual machine because it doesn’t
physically exist. It is a specification that provides a runtime environment in which Java bytecode can be
executed. It can also run those programs which are written in other languages and compiled to Java
bytecode. JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other. However, Java is
platform independent.
12 | P a g e
Object Oriented Programming in Java Lecture note
The Java compiler translates Java source code into bytecodes. Bytecodes are executed by the Java Virtual
Machine (JVM) – a part of the JDK and the foundation of the Java platform. A VM is a software application
that simulates a computer but hides the underlying operating system and hardware from the programs that
interact with it. If the same VM is implemented on many computer platforms, applications that it executes can
be used on all those platforms. The JVM is one of the most widely used virtual machines.
13 | P a g e
Object Oriented Programming in Java Lecture note
Unlike machine language, which is dependent on specific computer hardware, bytecodes are platform
independent. So, Java’s bytecodes are portable – without recompiling the source code, the same bytecodes can
execute on any platform. The JVM is invoked by the java command. For example, to execute a Java
application called Welcome, you’d type the command
14 | P a g e
Object Oriented Programming in Java Lecture note
Phase 5: Execution
In this, the JVM executes the program’s bytecodes, thus performing the actions specified by the program. The
JVM analyzes the bytecodes as they’re interpreted, searching for hot spots – parts of the bytecodes that
execute frequently. For these parts, a just-in-time (JIT) compiler – known as the Java HotSpot compiler –
translates the bytecodes into the underlying computer’s machine language. When the JVM encounters these
compiled parts again,
the faster machine-language code executes. Thus, Java programs actually go through two compilation phases
– one in which source code is translated into bytecodes (for portability across JVMs on different computer
platforms) and a second in which, during execution, the bytecodes are translated into machine language for
the actual computer on which the program executes.
Output:
15 | P a g e
Object Oriented Programming in Java Lecture note
The line numbers are displayed for reference purposes but are not part of the program. So, don’t type line
numbers in your program.
• Line 1 defines a package. It is a way of organizing a program at one place.
• Line 2 defines a class. Every Java program must have at least one class. Each class has a name. By
convention, class names start with an uppercase letter. In this example, the class name is Welcome.
• Line 3 defines the main method. In order to run a class, the class must contain a method named main.
The program is executed from the main method. A method is a construct that contains statements. The
main method in this program contains the System.out.println statement (line 4). This statement prints
a message “Welcome to Java!” to the console. Every statement in Java ends with a semicolon (;),
known as the statement terminator.
• A pair of braces in a program forms a block that groups the program’s components. In Java, each
block begins with an opening brace ({) and ends with a closing brace (}). Every class has a class block
that groups the data and methods of the class. Every method has a method block that groups the
statements in the method. Blocks can be nested, meaning that one block can be placed within another,
as shown in the following code.
Note:
Java source programs are case-sensitive. Example: main and Main are different.
16 | P a g e
Object Oriented Programming in Java Lecture note
The Java program-development process consists of repeatedly creating/modifying source code, compiling,
and executing programs.
From the command window, you can use the NotePad to create the Java source code file, as shown in Figure
below.
You can create the Java source file using Windows NotePad.
File Name:
The source file must end with the extension .java and must have exactly the same name as the public class
name. For example, the file for the source code above should be named Welcome.java, since the public class
name is Welcome.
Compile:
A Java compiler translates a Java source file into a Java bytecode file. The following command compiles
Welcome.java:
17 | P a g e
Object Oriented Programming in Java Lecture note
Note:
You must first install and configure JDK before compiling and running programs. “Installing and Configuring
JDK 6 or above,” on how to install JDK and set up the environment to compile and run Java programs.
.class bytecode file:
If there are no syntax errors, the compiler generates a bytecode file with a .class extension. So the preceding
command generates a file named Welcome.class, see figure (a) below. The Java language is a high-level
language while Java bytecode is a low-level language. The bytecode is similar to machine instructions but is
architecture neutral and can run on any platform that has a Java Virtual Machine (JVM), see figure (b) below.
Rather than a physical machine, the virtual machine is a program that interprets Java bytecode. This is one of
Java’s primary advantages: Java bytecode can run on a variety of hardware platforms and operating systems.
It normally starts with the coding step, in which the source code is written in any text editors or integrated
programming environment. In Java, source code files are usually saved with .java extension. Once the Java
source code is saved, it is compiled using a java compiler, such as javac.exe, to obtain the resulting Java
bytecode, which is also called a Java class. The actual Java class file is created with .class extension. Then,
the program is executed by running the command ‘java.exe’ on the class file. If the result appears as expected,
the cycle terminates. Otherwise, the source code has to be edited, then compiled and executed again. The
process of fixing the source code in order to obtain the right result is called ‘debugging’.
18 | P a g e
Object Oriented Programming in Java Lecture note
(a) Java source code is translated into bytecode. (b) Java bytecode can be executed on any computer with a
Java Virtual Machine.
Interpreting bytecode:
To execute a Java program is to run the program’s bytecode. You can execute the bytecode on any platform
with a JVM. Java bytecode is interpreted. Interpreting translates the individual steps in the bytecode into the
target machine-language code one at a time rather than translating the whole program as a single unit. Each
step is executed immediately after it is translated.
Run:
The following command runs the bytecode:
The following shows the javac command for compiling Welcome.java. The compiler generated
the Welcome.class file. This file is executed using the java command.
19 | P a g e