Fundamentals of Object-Oriented
Programming (OOP )
• OOP is an approach to program organization
and development, which attempts to eliminate
some of the pitfalls of conventional
programming methods by incorporating the
best of structured programming features with
several new concepts.
• Languages that support OOP features include
Smalltalk, C++, Ada and Pascal.
• C++ is basically a procedural language with
object-oriented extension.
• Java is a pure object-oriented language.
Features of Object-Oriented Paradigm
• Emphasis is on data rather than procedure.
• Programs are divided into what are known as Objects.
• Data structures are designed such that they characterize the
objects.
• Methods that operate on data of an object are tied together
in the data structure.
• Data is hidden and cannot be accessed by external functions.
• Objects may communicate with each other through methods.
• New data and methods can be easily added whenever
necessary.
• Follow bottom-up approach in program design.
Basic Concepts of OOP
• Objects and Classes
Objects are basic runtime entities in an OOP and
contains data & code to manipulate the data.
Eg : a person, a place, a bank a/c etc.
Any programming problem is analyzed in terms of
objects and the nature of communication between
them.
An object takes up space in the memory and has an
associated memory address.
A class is a user-defined data
A class is a collection of objects of similar type.
Eg : mango, apple and Orange are members of fruit.
• Data Abstraction & Encapsulation
The wrapping up of data and methods into a single
unit (called class) is known as encapsulation.
Data is not accessible to the outside world and only
those methods, which are wrapped in the class, can
access it.
These methods provide the interface between
object’s data and the program.
This insulation of the data from direct access by the
program is called Data Hiding.
Encapsulation makes it possible for objects to be
treated like ‘Black Boxes’.
Abstraction refers to the act of representing essential
features without including the background details.
Classes encapsulate all the essential properties of the
objects that are to be created.
Encapsulation is one of the 3 OOP principles, the other 2 are
inheritance & polymorphism.
• Inheritance
It is the process by which objects of one class
acquire the properties of objects of another class.
It supports the concept of hierarchical
classification.
It provides the idea of reusability, means that we
can add additional features to an existing class
without modifying it.
In Java, the derived class is known as ‘subclass’.
Each subclass defines only those features that are
unique to it.
Polymorphism
• It means the ability to take more than one form.
• Eg. An operation may exhibit different behaviour
in different instances.
• Eg. For 2 no.s, the addition operation will
generate a sum and if the operands are strings it
will generate a concatenated string.
• Polymorphism is extensively used in
implementing inheritance.
Dynamic Binding
• It means that the code associated with a given
procedure call is not known until the time of
call at runtime.
• Actually it is associated with inheritance
&Polymorphism.
Message Communication
• The process of programming in an object-
oriented language involves the following:
– Creating classes that define objects and their
behaviour
– Creating objects from class definition
– Establishing communication among objects.
• A message for an object is a request for
execution of a procedure.
• Therefore it will invoke a method(procedure)
in the receiving object that generates the
desired result
• Message passing involves specifying the name of the
object, the name of the method and the information
to be sent
• For eg: consider the statement
History of Java
• Java is a general-purpose, Object-oriented
programming language developed by Sun
Microsystems ( now Oracle corporation), of USA in
1991.
• Initially it was known as ‘oak’ by James Gosling,
one of the inventors of the language.
• Java was designed for the development of software
for consumer electronic devices such as TVs, VCRs,
Toasters and such other electronic machines.
• Later in 1995 ‘oak’ was renamed as Java due to
some legal issues.
Java Environment
• Java Development Kit (JDK) comes with a collection of tools
that are used for developing & running Java programs. They
include :
1. Appletviewer –enables us to run Java applets without using Java
compattible browser.
2. Javac – the Java Compiler which translates java source code to byte
code files that the interpreter can understand
3. Java – Java Interpreter, which runs applets and aplications by
reading & interpreting byte code files.
4. Javap - Java disassembler, which enables us to convert bytecode
files into a program description (source code).
5. Jdb – Java debugger, which helps us to find errors in our program.
6. Javadoc – creates HTML format documentation from Java source
code files.
7. Javah – produces header files for use with native methods (C
header files)
Features
• Compiled and Interpreted – Java is a 2 stage
programming language
source code->bytecode ->machine code
• Platform Independent(Architecture-Neutral) and
portable - changes & upgrades in OSs , processors &
system resources will not change in java programs.
”write once;run anywhere, anytime, forever.”
Portable means same code must work on all
computers. The execution of bytecode is very easiest
on any machine.
• Object-oriented – Java is a true object-oriented language.
everything in Java is an object. All program code & data
reside within objects & classes.
Java comes with an extensive set of classes, arranged in
Packages, that we can use in our programs by Inheritance.
The object model in Java is simple & easy to extend.
• Robust & Secure - provide many safeguards to gain
reliability. It checks your code at both compile & runtime
(exception handling). It is designed as a garbage collected
language relieving all memory management problems.
It is an important issue for a lang. that is used for
programming on Internet. Java verifies all memory access and
ensures that no viruses are communicated with an applet.
Absence of pointers ensures programs cannot gain access to
memory locations without proper authorization.
• Distributed – Multiple progmers at multiple
remote locations to collaborate & work together
on a single project. Java supports RMI(Remote
Method Invocation) enables a program to invoke
methods across a n/w.
• Familiar, Simple & Small – if you already
understand the basic OOPs concepts, learning Java
will be easier. it does not use pointers, go to
statement, pre-processor header files etc. Also
eliminates operator overloading &multiple
inheritance.
• Multithreaded & Interractive – Java supports
multithreaded programing, which allows to write
programs that do many things simultaneously. We need
not wait for the application to finish one task before
beginning other. It improves performance.
• High Performance - high performance due to the
intermediate bytecode. Java architecture is also designed
to reduce overheads during runtime. Incorporation of
multithreading improves speed and performance.
• Dynamic & extensible – Java is capable of linking in new
class libraries, methods & objects. Java programs
support functions(native methods) written in other
languages such as C & C++. They are linked dynamically
at runtime.
First simple Java pgm
/* this is a simple java pgm
save this file as “Example.java” */
class Example
{
// your pgm begins here
public static void main(String args[])
{
System.out.println(“Welcome to Java pgm”);
}
}
The filename should be “Example.java”
Compiling the program
C:\>javac Example.java
Compiler creates a file called Example.class
contains bytecode version.
To run pgm
C:\> java Example
The following o/p is displayed
Welcome to Java pgm
• Pgm execution begins with main()
• The public keyword is access specifier, which
allows the programer to control the visibility
of class members.
• public – members are accessed by code
outside the class in which it is declared.
( accessible to all other classes)
• private – which prevents a member from
being used by code defined outside of its
class.
• static allows main() to be called without
having to instantiate a particular instance of
the class. This is necessary since main() is
called by JVM before any objects are made.
• void tells compiler that main() does not return
a value.
• String args[] – declares a parameter named
args, which contains an array of objects of the
class type String.
• Every java statement end with a semicolon.
• The println method is a member of the out
object, which is a static data member of the
System class
• println always appends a newline character to
the end of the string.
• Java is case-sensitive.
Second short program
/* More java statements
This code computes square root */
import java.lang.Math; // tells the interpreter to load Math
//class from package lang
class SquareRoot
{
public static void main(String args[ ])
{
double x = 5; // declaration & initialization
double y; // simple declaration
y = Math.sqrt(x); // invokes sqrt of Math class
System.out.println(“y = ” + y );
}
Java Program Structure
Java Tokens
• Smallest individual units in a program are known
as tokens.
• The compiler recognizes them for building up
expressions and statements.
• Java language includes 5types of tokens:
- Reserved keywords
- Identifiers
– Literals
– Operators
– Separators
Java Character set
• The smallest unit of Java language are the
characters used to write Java tokens.
• The characters are defined by the Unicode
character set.
• It is a 16 bit character coding system supports
more than 34000 defined characters derived
from 24 languages.
• But most of us use only the basic ASCII (a subset
of Unicode character set) characters in
developing the programs.
Keywords
- They have pre-defined meanings.
- 50 keywords in Java.
- they cannot be used as names for a variables,
classes , methods and so on.
Eg: for, continue, abstract, long, native, case,
class, const, import, enum, extends, final, catch ,
protected, try, void, throw, etc.
Identifiers
They are programmer-designed tokens.
they are used for naming variables, classes ,
methods, objects, packages, interfaces and so on.
It must be meaningful, short, descriptive and
easily read.
Java identifiers follow the following rules:
They can have alphabets, digits, underscore & dollar
sign characters.
They must not begin with a digit.
Uppercase & lowercase letters are distinct.
They can be of any length.
Literals (constants)
-a sequence of characters (digits, letters, & other
characters) that represent constant values to be
stored in variables. Java specifies 5 types of
literals:
- integer literals
- floating-point literals
- character literals
- string literals
-Boolean literals
Operators
• An operator is a symbol that takes one or more
arguments and operate on them to produce a result.
Separators
• They are symbols used to indicate where groups of code
are divided and arranged.
Java Statements
• It is an executable combination of tokens
ending with a semicolon(;)mark.
• They are usually executed in sequence in the
order in which they appear.
• However it is possible to control the flow of
execution using special statements.
Implementing Java Program
Creating the Program:
Save this program as Test.java. This file is called Source File.
Compiling the Program
javac Test.java
If everything OK, javac compiler creates a file called Test.class containing the
bytecode of the program.
Running the Program
We need java interpreter to run the program. At the command prompt type
java Test
Interpreter looks for the main method & begins execution from there and
shows the o/p.
Command Line Arguments
• They are parameters that are supplied to the
application program at the time of invoking it for
execution.
• We can write Java programs that can receive & use
the arguments provided in the command line.
• args is declared as an array of strings(known as
string objects).
• Any arguments provided in the command line are
passed to the array args as its elements.
• We can simply access the array elements & use
them as we wish.
For Eg : consider the command line
java Test BASIC FORTRAN C++ JAVA
This command line contains 4 arguments.
These are assigned to the array args as follows:
args[0] BASIC
args[1] FORTRAN
args[2] C++
args[3] JAVA
The individual elements of array are accessed by using
index or subscript like args[i].
Save file as ComLineTest.java
Compile as javac ComLineTest.java
Run as
java ComLineTest Simple Robust Secure Portable
The o/p of the prgm is as follows:
Number of arguments = 4
1 : Java is Simple!
2 : Java is Robust!
3 : Java is Secure!
4 : Java is Portable!
Constants, Variables & Data Types
• The task of processing data is accomplished
by executing a sequence of instructions
constituting a program.
• These instructions are formed using certain
symbols & words according to some rules
known as syntax rules(or grammer).
Constants (Literals)
• Refer to fixed values that don't change during
the execution of a program.
• Java supports several types of constants:
Variables
Data Types
• Every variable in Java has a data type.
• It specify the type & size of values that can be stored.
Integer
• It can hold whole numbers.
• Support 4 types of integers byte, short, int & long.
• It doesn’t support the concept of unsigned type. i.e all java
values are signed.
Floating-point
• It can hold numbers containing fractional numbers.
• float - Holds single-precision values. The execution faster on
some processors. floats can be useful when representing
dollars & cents.
• double - Holds double-precision values. Useful for high
accuracy calculations. faster than float on some modern
processors.
Character
• char type holds a single character.
• 2 bytes(16 bit) size.
• Range is 0 – 65,536
• There are no –ve chars
Boolean
• boolean can have one of the 2 possible
values, true or false
• It uses only 1 bit of storage.
• This is the type returned by all comparison
operators.
• Also used in selection iteration statements.
• The words true & false cannot be used as
identifiers.
Declaration of Variables
Giving Values to Variables
OUTPUT
Scope of Variables
Symbolic Constants
• Constants are fixed values. It cannot change
during the execution of the program.
• Constants encounter 2 problems while using in
programs :
– Problem in modification of the program
– Constants may appear repeatedly in number of places in the
program. If there is any change in the value it will be difficult to
change every appearance of it.
– Problem in understanding the program
– When a numeric value appears in the program, its use is always
not clear. When we go through the program in future we may
forget what the number really means.
• Symbolic constants in Java are named constants.
• The subsequent use of these name in the program has the
effect of caving their defined values to be automatically
substituted in appropriate points. The constant is declared
as follows:
Rules :-
• symbolic names take the some form as variable names. But they one
written in capitals to distinguish from variable names. This is only
convention not a rule.
• After declaration of symbolic constants they shouldn’t be assigned
any other value with in the program by using an assignment
statement.
For eg:- STRENTH = 200 is illegal
• In C & C++ symbolic constants are defined using the #define
statement.
• They can’t be declared inside a method . they should be used only as
class data members in the beginning of the class.
Type Casting
Getting Values of Variables
Standard Default Values