Unit 01 INTRODUCTION TO OOP AND JAVA
FUNDAMENTALS
1.1 OBJECT-ORIENTED PROGRAMMING
Object-oriented programming (OOP) is a programming paradigm based on the concept of
“objects”, which may contain data, in the form of fields, often known as attributes; and code,
in the form of procedures, often known as methods.
Object-Oriented Programming:
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or methods that perform operations
on the data, while object-oriented programming is about creating objects that contain both
data and methods.
Object-oriented programming has several advantages over procedural programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
OOP makes it possible to create full reusable applications with less code and shorter
development time.
The diagram below demonstrates the Java OOPs Concepts
List of object-oriented programming languages
Ada 95 Fortran 2003 PHP since v4, greatly enhanced in v5
BETA Graphtalk Python
C++ IDLscript Ruby
C# J# Scala
COBOL Java Simula
Cobra LISP Smalltalk
ColdFusion Objective-C Tcl
Common Lisp Perl since v5
Abstraction
Abstraction is one of the key concepts of object-oriented programming (OOP)
languages. Its main goal is to handle complexity by hiding unnecessary details from the
user. This en- ables the user to implement more complex logic on top of the provided
abstraction without understanding about all the hidden complexity.
For example, people do not think of a car as a set of tens of thousands of individual
parts. They think of it as a well-defined object with its own unique behavior. This
abstraction allows people to use a car to drive to the desired location without worrying
about the complexity of the parts that form the car. They can ignore the details of how the
engine, transmission, and braking systems work. Instead, they are free to utilize the object
as a whole.
A powerful way to manage abstraction is through the use of hierarchical classifications. This
allows us to layer the semantics of complex systems, breaking them into more manage- able
pieces.
Hierarchical abstractions of complex systems can also be applied to computer
programs.
The data from a traditional process-oriented program can be transformed by abstraction
into its component objects.
A sequence of process steps can become a collection of messages between these
objects.
Thus, each of these objects describes its own unique behavior.
We can treat these objects as concrete entities that respond to messages telling them
to do something.
Objects And Classes
Object
Objects have states and behaviors. Example: A dog has states - color, name, breed as well
as behaviors – wagging the tail, barking, eating. An object is an instance of a class.
Class
A class can be defined as a template/blueprint that describes the behavior/state that the
object of its type support.
Objects in Java
If we consider the real-world, we can find many objects around us, cars, dogs, humans,
etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.
If we compare the software object with a real-world object, they have very similar char-
acteristics.
Software objects also have a state and a behavior. A software object’s state is stored in
fields and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the
object-to-object communication is done via methods.
Classes in Java
A class is a blueprint from which individual objects are created.
Following is an example of a class.
public class Dog {
String breed;
int age;
String color;
void barking()
{
}
}
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and
the variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside
any method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods.
In the above example, barking(), hungry() and sleeping() are methods.
Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse.
In Java, the basis of encapsulation is the class. There are mechanisms for hiding the
complexity of the implementation inside the class.
Each method or variable in a class may be marked private or public.
The public interface of a class represents everything that external users of the class
need to know, or may know.
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.
Since the private members of a class may only be accessed by other parts of program
through the class’ public methods, we can ensure that no improper actions take place.
Inheritance
Inheritance is the process by which one object acquires the properties of another object.
For example, a Dog is part of the classification Mammal, which in turn is part of the Ani-
mal class. Without the use of hierarchies, each object would need to define all of its charac-
teristics 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,
inheritance makes it possible for one object to be a specific instance of a more general case.
Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface
to be used for a general class of actions. The specific action is determined by the exact nature
of the situation.
For eg, a dog’s sense of smell is polymorphic. If the dog smells a cat, it will bark and run
after it. If the dog smells its food, it will salivate and run to its bowl. The same sense of smell
is at work in both situations. The difference is what is being smelled, that is, the type of data
being operated upon by the dog’s nose.
Consider a stack (which is a last-in, first-out LIFO list). We might have a program that re-
quires three types of stacks. One stack is used for integer values, one for floating-point values,
and one for characters. The algorithm that implements each stack is the same, even though
the data being stored differs.
1.2 OOP CONCEPTS IN JAVA
OOP concepts in Java are the main ideas behind Java’s Object Oriented Programming.
They are:
Introduction to Oop and Java Fundamentals 1.5
Object
Any entity that has state and behavior is known as an object. It can be either physical or
logical.
For example: chair, pen, table, keyboard, bike etc.
Class & Instance
Collection of objects of the same kind is called class. It is a logical entity.
A Class is a 3-Compartment box encapsulating data and operations as shown in figure.
Class Name
Static Attributes
Dynamic Behaviors
Figure: Class Structure
The followings figure shows two classes ‘Student’ and ‘Circle’.
Name (Identifier) Student Circle
Variables (Static Attributes) name, gender, dept, marks radius, color
Methods getDetails() getRadius()
(Dynamic Behaviors) calculateGrade() printArea()
Figure: Examples of classes
A class can be visualized as a three-compartment box, as illustrated:
1. Name (or identity): identifies the class.
2. Variables (or attribute, state, field): contain the static attributes of the class.
3. Methods (or behaviors, function, operation): contain the dynamic behaviors of the
class.
An instance is an instantiation of a class. All the instances of a class have similar proper-
ties, as described in the class definition. The term “object” usually refers to instance.
For example, we can define a class called “Student” and create three instances of the class
“Student” for “John”, “Priya” and “Anil”.
The following figure shows three instances of the class Student, identified as “John”,
“Priya” and “Anil”.
1.6 Object Oriented Programming
John : Student Priya : Student Anil : Student
name = “John” name = “Priya” name = “Anil”
gender = “male” gender = “female” gender = “male”
dept = “CSE” gender = “female” gender = “male”
mark = 88 dept = “IT” dept = “IT”
getDetails() getDetails() getDetails()
calculateGrade() calculateGrade() calculateGrade()
Figure: Instances of a class ‘Student’
Abstraction
Abstraction refers to the quality of dealing with ideas rather than events. It basically deals
with hiding the details and showing the essential things to the user.
We all know how to turn the TV on, but we don’t need to know how it works in order to
enjoy it.
Abstraction means simple things like objects, classes, and variables represent more com-
plex underlying code and data. It avoids repeating the same work multiple times. In java, we
use abstract class and interface to achieve abstraction.
Abstract class:
Abstract class in Java contains the ‘abstract’ keyword. If a class is declared abstract, it
cannot be instantiated. So we cannot create an object of an abstract class. Also, an abstract
class can contain abstract as well as concrete methods.
To use an abstract class, we have to inherit it from another class where we have to provide
implementations for the abstract methods there itself, else it will also become an abstract
class.
Interface:
Interface in Java is a collection of abstract methods and static constants. In an interface,
each method is public and abstract but it does not contain any constructor. Along with ab-
straction, interface also helps to achieve multiple inheritance in Java.
So an interface is a group of related methods with empty bodies.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
It means to hide our data in order to make it safe from any modification.
The best way to understand encapsulation is to look at the example of a medical capsule,
where the drug is always safe inside the capsule. Similarly, through encapsulation the meth-
ods and variables of a class are well hidden and safe.
A java class is the example of encapsulation.
Encapsulation can be achieved in Java by:
Declaring the variables of a class as private.
Providing public setter and getter methods to modify and view the variables values.
Inheritance
This is a special feature of Object Oriented Programming in Java. It lets programmers
create new classes that share some of the attributes of existing classes.
For eg, a child inherits the properties from his father.
Similarly, in Java, there are two classes:
1. Parent class (Super or Base class)
2. Child class (Subclass or Derived class)
A class which inherits the properties is known as ‘Child class’ whereas a class whose
properties are inherited is known as ‘Parent class’.
Inheritance is classified into 4 types:
Single Inheritance
It enables a derived class to inherit the properties and behavior from a single parent
class.
Here, Class A is a parent class and Class B is a child class which inherits the properties
and behavior of the parent class.
Multilevel Inheritance
When a class is derived from a class which is also derived from another class, i.e. a class
having more than one parent class but at different levels, such type of inheritance is called
Multilevel Inheritance.
Here, class B inherits the properties and behavior of class A and class C inherits the prop-
erties of class B. Class A is the parent class for B and class B is the parent class for C. So, class
C implicitly inherits the properties and methods of class A along with Class B.
Hierarchical Inheritance
When a class has more than one child class (sub class), then such kind of inheritance is known
as hierarchical inheritance.
Here, classes B and C are the child classes which are inheriting from the parent class A.
Hybrid Inheritance
Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.
Since multiple inheritance is not supported in Java as it leads to ambiguity, this type of inheri-
tance can only be achieved through the use of the interfaces.
Here, class A is a parent class for classes B and C, whereas classes B and C are the parent
classes of D which is the only child class of B and C.
Polymorphism
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means
forms. It is the ability of a variable, function or object to take on multiple forms. In other
words, polymorphism allows us to define one interface or method and have multiple imple-
mentations.
For eg, Bank is a base class that provides a method rate of interest. But, rate of interest
may differ according to banks. For example, SBI, ICICI and AXIS are the child classes that
provide different rates of interest.
Polymorphism in Java is of two types:
Run time polymorphism
Compile time polymorphism
Run time polymorphism:
In Java, runtime polymorphism refers to a process in which a call to an overridden method
is resolved at runtime rather than at compile-time. Method overriding is an example of run
time polymorphism.
Compile time polymorphism:
In Java, compile time polymorphism refers to a process in which a call to an overloaded
method is resolved at compile time rather than at run time. Method overloading is an example
of compile time polymorphism.
1.3 CHARACTERISTICS OF JAVA
Simple :
Java is Easy to write and more readable.
Java has a concise, cohesive set of features that makes it easy to learn and use.
Most of the concepts are drawn from C++, thus making Java learning simpler.
1.10 Object Oriented Programming
Secure :
Java program cannot harm other system thus making it secure.
Java provides a secure means of creating Internet applications.
Java provides secure way to access web applications.
Portable :
Java programs can execute in any environment for which there is a Java run-time
system.
Java programs can run on any platform (Linux, Window, Mac)
Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
Java programming is object-oriented programming language.
Like C++, java provides most of the object oriented features.
Java is pure OOP Language. (while C++ is semi object oriented)
Robust :
Java encourages error-free programming by being strictly typed and performing run-
time checks.
Multithreaded :
Java provides integrated support for multithreaded programming.
Architecture-neutral :
Java is not tied to a specific machine or operating system architecture.
Java is machine independent.
Interpreted :
Java supports cross-platform code through the use of Java bytecode.
Bytecode can be interpreted on any platform by JVM (Java Virtual Machine).
High performance :
Bytecodes are highly optimized.
JVM can execute bytecodes much faster .
Distributed :
Java is designed with the distributed environment.
Java can be transmitted over internet.
Dynamic :
Java programs carry substantial amounts of run-time type information with them that
is used to verify and resolve accesses to objects at run time.
1.4 JAVA RUNTIME ENVIRONMENT (JRE)
The Java Runtime Environment (JRE) is a set of software tools for development of Java
applications. It combines the Java Virtual Machine (JVM), platform core classes and support-
ing libraries.
JRE is part of the Java Development Kit (JDK), but can be downloaded separately. JRE
was originally developed by Sun Microsystems Inc., a wholly-owned subsidiary of Oracle
Corporation.
JRE consists of the following components:
Name of the component Elements of the component
Deployment technologies Deployment
Java Web Start
Java Plug-in
User interface toolkits Abstract Window Toolkit (AWT)
Swing
Java 2D
Accessibility
Image I/O
Print Service
Sound
Drag and Drop (DnD)
Input methods.
Integration libraries Interface Definition Language (IDL)
Java Database Connectivity (JDBC)
Java Naming and Directory Interface (JNDI)
Remote Method Invocation (RMI)
Remote Method Invocation Over Internet
Inter-Orb Protocol (RMI-IIOP)
Scripting.
base libraries International support
Input/Output (I/O)
Eextension mechanism
Beans
Java Management Extensions (JMX)
Java Native Interface (JNI)
Math
Networking
Override Mechanism
Security
Serialization and Java for XML Processing
(XML JAXP).
Lang and util base libraries lang and util
Management
Versioning
Zip
Instrument
Reflection
Collections
Concurrency
Java Archive (JAR)
Logging
Preferences API
Ref Objects
Regular Expressions.
Java Virtual Machine (JVM) Java HotSpot Client
Server Virtual Machines
1.5 JAVA VIRTUAL MACHINE (JVM)
The JVM is a program that provides the runtime environment necessary for Java pro-
grams to execute. Java programs cannot run without JVM for the appropriate hardware and
OS platform.
Java programs are started by a command line, such as:
java <arguments> <program name>
This brings up the JVM as an operating system process that provides the Java runtime
environment. Then the program is executed in the context of an empty virtual machine.
When the JVM takes in a Java program for execution, the program is not provided as Java
language source code. Instead, the Java language source must have been converted (or
compiled) into a form known as Java bytecode. Java bytecode must be supplied to the JVM
in a format called class files. These class files always have a .class extension.
The JVM is an interpreter for the bytecode form of the program. It steps through one
bytecode instruction at a time. It is an abstract computing machine that enables a computer to
run a Java program.
1.6 SETTING UP AN ENVIRONMENT FOR JAVA
Local Environment Setup
Download Java and run the .exe to install Java on the machine.
Setting Up the Path for Windows
Assuming Java is installed in c:\Program Files\java\jdk directory −
Right-click on ‘My Computer’ and select ‘Properties’.
Click the ‘Environment variables’ button under the ‘Advanced’ tab.
Now, alter the ‘Path’ variable so that it also contains the path to the Java executable.
Example, if the path is currently set to ‘C:\WINDOWS\SYSTEM32’, then change
your path to read ‘C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin’.
1.7 POPULAR JAVA EDITORS
To write Java programs, we need any of the following:
Notepad − Text editor
Netbeans − A Java IDE that is open-source and free
Eclipse − A Java IDE developed by the eclipse open-source community
1.8 JAVA SOURCE FILE STRUCTURE
When we write a Java source program, it needs to follow a certain structure or template
as shown in the following figure:
Figure: Java Source File Structure
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Java source file can have the following elements that must be specified in the following
order:
1. An optional package declaration to specify a package name.
2. Zero or more import declarations.
3. Any number of top-level type declarations. Class, enum, and interface declarations
are collectively known as type declarations.
Part 1: Optional Package Declaration
A package is a pack (group) of classes, interfaces and other packages. Packages are used
in Java in order to prevent naming conflicts, to control access, to make searching / locating
and usage of classes, interfaces, enumerations and annotations easier, etc.
Rules:
The package statement should be the first line in the source file.
There can be only one package statement in each source file.
If a package statement is not used, the class, interfaces, enumerations, and annotation
types will be placed in the current default package.
It is a good practice to use names of packages with lower case letters to avoid any
conflicts with the names of classes and interfaces.
Following package example contains interface named animals:
/* File name : [Link] */
package animals;
interface Animal
{
public void eat();
public void travel();
}
Part 2: Zero or More import Declarations
The import statement makes the declarations of external classes available to the current
Java source program at the time of compilation. The import statement specifies the path for
the compiler to find the specified class.
Syntax of the import statement:
import packagename;
or
import packagename.* ;
We may import a single class or all the classes belonging to a package.
To import a single class, we specify the name of the class
To import all classes, we specify *.
Examples of the import statement:
Statement in Java Purpose
import [Link]; imports the definition of the MyClass
class that is defined in the mypackage
package.
import [Link]. imports the definition of EmpClass
EmpClass; belonging to the [Link].
[Link] package.
import [Link].*; imports all the classes belonging to the
[Link] package.
Part 3: Zero or More top-level Declarations
The Java source file should have one and only one public class. The class name which is
defined as public should be the name of Java source file along with .java extension.
Source File Declaration Rules
There can be only one public class per source file.
A source file can have multiple non-public classes.
The public class name should be the name of the source file which should have
.java extension at the end.
For eg, if the class name is public class Employee{}, then the source file should be
as [Link].
If the class is defined inside a package, then the package statement should be the first
statement in the source file.
If import statements are present, then they must be written between the package
statement and the class declaration. If there are no package statements, then the
import statement should be the first line in the source file.
Import and package statements will imply to all the classes present in the source file.
It is not possible to declare different import and/or package statements to different
classes in the source file.
1.9 COMPILATION
In Java, programs are not compiled into executable files. Java source code is compiled
into bytecode using javac compiler. The bytecodes are platform-independent instructions for
the Java VM. They are saved on the disk with the file extension .class. When the program
is to be run, the bytecode is converted into the machine code using the just-in-time (JIT) com-
piler. It is then fed to the memory and executed.
Java code needs to be compiled twice in order to be executed:
1. Java programs need to be compiled to bytecode.
2. When the bytecode is run, it needs to be converted to machine code.
The Java classes / bytecode are compiled to machine code and loaded into memory by the JVM
when needed for the first time.
Compiling the Program
The Java compiler is invoked at the command line with the following syntax:
javac [Link]
Interpreting and Running the Program
Once the java program successfully compiles into Java bytecodes, we can interpret and run
applications on any Java VM, or interpret and run applets in any Web browser with a Java VM built
in such as Netscape or Internet Explorer. Interpreting and running a Java program means invoking
the Java VM byte code interpreter, which converts the Java byte codes to platform-dependent
machine codes so your computer can understand and run the program.
The Java interpreter is invoked at the command line with the following syntax:
java ExampleProgram
Quick compilation procedure
To execute the first Java program, follow the steps:
1. Open text editor. For example, Notepad or Notepad++ on Windows; Gedit, Kate or SciTE
on Linux; or, XCode on Mac OS, etc.
2. Type the java program in a new text document.
3. Save the file as [Link].
4. Next, open any command-line application. For example, Command Prompt on
Windows; and, Terminal on Linux and Mac OS.
5. Compile the Java source file using the command: javac [Link]
6. Once the compiler returns to the prompt, run the application using the following
command:
java HelloWorld