0% found this document useful (0 votes)
32 views

Object Oriented Programming (Java) Lecture Notes Unit 1

The document discusses object-oriented programming concepts like objects, classes, inheritance, encapsulation, abstraction and polymorphism. It explains that OOP uses objects that contain data and code. Classes define object types and objects are instances of classes. Encapsulation binds data and methods together and hides internal details. Inheritance allows code reuse by extending classes. Polymorphism allows the same function to have different implementations.

Uploaded by

Aditi Goel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Object Oriented Programming (Java) Lecture Notes Unit 1

The document discusses object-oriented programming concepts like objects, classes, inheritance, encapsulation, abstraction and polymorphism. It explains that OOP uses objects that contain data and code. Classes define object types and objects are instances of classes. Encapsulation binds data and methods together and hides internal details. Inheritance allows code reuse by extending classes. Polymorphism allows the same function to have different implementations.

Uploaded by

Aditi Goel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Unit - 1 Lecture Notes (Object Oriented Programming)

Introduction to Object Oriented Programming


Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can
contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of
procedures (often known as methods).

A feature of objects is that an object's own procedures can access and often modify the data fields of itself. In OOP,
computer programs are designed by making them out of objects that interact with one another. OOP languages are
diverse, but the most popular ones are class-based, meaning that objects are instances of classes, which also
determine their types.

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun
Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called
“Oak,” but was renamed “Java” in 1995. Between the initial implementation of Oak in the fall of 1992 and the
public announcement of Java in the spring of 1995, many more people contributed to the design and evolution of
the language.

Objects and Classes


Languages that support object-oriented programming (OOP) typically use inheritance for code reuse and
extensibility in the form of either classes or prototypes. Those that use classes support two main concepts:

 Classes – the definitions for the data format and available procedures for a given type or class of object; may
also contain data and procedures (known as class methods) themselves, i.e. classes contain the data members
and member functions

 Objects – instances of classes

Objects sometimes correspond to things found in the real world. For example, a graphics program may have
objects such as "circle", "square", "menu". An online shopping system might have objects such as "shopping cart",
"customer", and "product". Sometimes objects represent more abstract entities, like an object that represents an
open file, or an object that provides the service of translating measurements from U.S. customary to metric.

Each object is said to be an instance of a particular class (for example, an object with its name field set to "Mary"
might be an instance of class Employee). Procedures in object-oriented programming are known as methods;
variables are also known as fields, members, attributes, or properties. This leads to the following terms:

 Class variables – belong to the class as a whole; there is only one copy of each one

 Instance variables or attributes – data that belongs to individual objects; every object has its own copy of each
one

 Member variables – refers to both the class and instance variables that are defined by a particular class

 Class methods – belong to the class as a whole and have access only to class variables and inputs from the
procedure call

@Mragank Singhal P a g e |1
Unit - 1 Lecture Notes (Object Oriented Programming)
 Instance methods – belong to individual objects, and have access to instance variables for the specific object
they are called on, inputs, and class variables

Objects are accessed somewhat like variables with complex internal structure, and in many languages are
effectively pointers, serving as actual references to a single instance of said object in memory within a heap or
stack. They provide a layer of abstraction which can be used to separate internal from external code. External code
can use an object by calling a specific instance method with a certain set of input parameters, read an instance
variable, or write to an instance variable. Objects are created by calling a special type of method in the class known
as a constructor. A program may create many instances of the same class as it runs, which operate independently.
This is an easy way for the same procedures to be used on different sets of data.

Abstraction

Abstraction is the concept of object-oriented programming that "shows" only essential attributes and "hides"
unnecessary information. The main purpose of abstraction is hiding the unnecessary details from the users.
Abstraction is selecting data from a larger pool to show only relevant details of the object to the user. It helps in
reducing programming complexity and efforts. It is one of the most important concepts of OOPs.

Encapsulation

Encapsulation is an object-oriented programming concept that binds together the data and functions that
manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the
important OOP concept of data hiding. This concept is also often used to hide the internal representation, or state,
of an object from the outside. This is called information hiding. The general idea of this mechanism is simple. If you
have an attribute that is not visible from the outside of an object, and bundle it with methods that provide read or
write access to it, then you can hide specific information and control access to the internal state of the object.

Difference between Abstraction and Encapsulation

Abstraction Encapsulation
Abstraction in Object Oriented Programming solves
Encapsulation solves it implementation level.
the issues at the design level.
Abstraction in Programming is about hiding unwanted Encapsulation means binding the code and data into a
details while showing most essential information. single unit.
Encapsulation means hiding the internal details or
Data Abstraction in Java allows focusing on what the
mechanics of how an object does something for
information object must contain.
security reasons.

@Mragank Singhal P a g e |2
Unit - 1 Lecture Notes (Object Oriented Programming)
Inheritance

The importance of inheritance should never be treated lightly because the aim of inheritance is “reusability.” What
inheritance does, as the name would imply, is that it allows the code written in a class to be extended into another
class. So, in inheritance, there exists a base class; the class in which the code is written is to be reused.

The next class that we would create would have to be inherited from this base class to use all the functions and
variables associated with the base class. Whenever a class takes the properties of another class (or inherits from a
different class), all the members who are present in the base class become a member of this new derived class.

Polymorphism

The basic definition of the word polymorphism means having many forms. This definition holds very accurately in
explaining polymorphism in the context of programming. In this paradigm, polymorphism takes the meaning of one
function but many forms. Polymorphism actually happens at compile time. Polymorphism at compile time is only
possible because of the concept of overloading, and at run time, the feature of overriding makes polymorphism a
reality. Overloading requires the code that you write or the class’s function to be written more than once with
different parameters but having the same return type. It means that the arguments that you pass into the function
can be different, and just by looking at the final values which are passed into the function at run time, which form
of the function is to be called is decided. Generally, we see the class constructor be the most overloaded function.

Differences between Inheritance and Polymorphism

1. Inheritance is essentially making a class, and then having other classes in your program get their feature form
the already existing base class. However, polymorphism is an interface, and because of being an interface, it
can take different shapes and forms.

2. Inheritance is a property pertaining to just classes whereas; polymorphism extends itself into any method
and/or function.

3. Inheritance allows the derived class to use all the functions and variables declared in the base class without
explicitly defining them again. That is why we say that inheritance increases the code reusability and reduces
the length of code, which we would have to write if the inheritance was absent. Whereas, polymorphism allows
for the same function name to have two very different codes. So, in a sense, instead of reducing the length of
the code which we would have to write, polymorphism is extending it further.

4. There are many forms that inheritance can take; you can be really creative with inheritance. However,
polymorphism can only be accomplished by two means, i.e., overloading and overriding. You can still go very
crazy while using polymorphism, but you are restricted to just the two ways of implementing it into your
writing code.

@Mragank Singhal P a g e |3
Unit - 1 Lecture Notes (Object Oriented Programming)

Characteristics of Java
The key characteristics were summed up by the Java team in the following list of buzzwords:

Simple

Java was designed to be easy for the professional programmer to learn and use effectively. If you already
understand the basic concepts of objectoriented programming, learning Java will be even easier. Best of all, if you
are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++
syntax and many of the object-oriented features of C++, most programmers have little trouble learning Java.

Object-Oriented

Java is true object oriented language. Almost “Everything is an Object” paradigm is followed. All program code and
data reside within objects and classes. The object model in Java is simple and easy to extend. Java comes with an
extensive set of classes, arranged in packages that can be used in our programs through inheritance.

Distributed

Java is designed for distributed environment of the Internet. It is used for creating applications on networks. Java
applications can access remote objects on Internet as easily as they can do in local system. Java enables multiple
programmers at multiple remote locations to collaborate and work together on a single project.

Compiled and Interpreted

Usually a computer language is either compiled or interpreted. Java combines both this approach and makes it a
two-stage system. Compiled: Java enables creation of a cross platform programs by compiling into an intermediate
representation called Java Bytecode. Interpreted: Bytecode is then interpreted, which generates machine code that
can be directly executed by the machine that provides a Java Virtual machine.

Robust

It provides many features that make the program execute reliably in variety of environments. Java is a strictly typed
language. It checks code both at compile time and runtime. Java takes care of all memory management problems
with garbage-collection. Java, with the help of exception handling captures all types of serious errors and
eliminates any risk of crashing the system.

Secure

Java provides a “firewall” between a networked application and your computer. When a Java Compatible Web
browser is used, downloading can be done safely without fear of viral infection or malicious intent. Java achieves
this protection by confining a Java program to the java execution environment and not allowing it to access other
parts of the computer.

@Mragank Singhal P a g e |4
Unit - 1 Lecture Notes (Object Oriented Programming)

Architecture Neutral

Java language and Java Virtual Machine helped in achieving the goal of “write once; run anywhere, any time,
forever.” Changes and upgrades in operating systems, processors and system resources will not force any changes
in Java Programs.

Portable

Java provides a way to download programs dynamically to all the various types of platforms connected to the
Internet. It helps in generating Portable executable code.

High Performance

Java performance is high because of the use of bytecode. The bytecode was used, so that it was easily translated
into native machine code.

Multithreaded

Multithreaded Programs handled multiple tasks simultaneously, which was helpful in creating interactive,
networked programs. Java run-time system comes with tools that support multiprocess synchronization used to
construct smoothly interactive systems.

Dynamic

Java is capable of linking in new class libraries, methods, and objects. It can also link native methods (the functions
written in other languages such as C and C++).

The Java Environment


The Java Runtime Environment, or JRE, is a software layer that runs on top of a computer’s operating system
software and provides the class libraries and other resources that a specific Java program needs to run.

The JRE is one of three interrelated components for developing and running Java programs. The other two
components are as follows:

 The Java Development Kit, or JDK, is a set of tools for developing Java applications. Developers choose JDKs by
Java version and by package or edition—Java Enterprise Edition (Java EE), Java Special Edition (Java SE), or Java
Mobile Edition (Java ME). Every JDK always includes a compatible JRE, because running a Java program is part
of the process of developing a Java program.

 The Java Virtual Machine, or JVM, executes live Java applications. Every JRE includes a default JRE, but
developers are free to choose another that meets the specific resource needs of their applications.

The JRE combines Java code created using the JDK with the necessary libraries required to run it on a JVM and then
creates an instance of the JVM that executes the resulting program. JVMs are available for multiple operating

@Mragank Singhal P a g e |5
Unit - 1 Lecture Notes (Object Oriented Programming)
systems, and programs created with the JRE will run on all of them. In this way, the Java Runtime Environment is
what enables a Java program to run in any operating system without modification.

Java Source File Structure


A Java program can contain any number of classes but at most one class can be declared as the public. If there is a
public class then the name of the program and name of the public class must be matched otherwise we will get
compile time error. If there is no public class then we can use any name as Java source file name, there are no
restrictions.

class A {
}
class B {
}
class C {
}

Save as
Hello.java // Fine
Abc.java // Fine
P.java // Fine

Case 1:

If there is no public class then we can use any name as Java source file name.

E.g.
 A.java
 B.java
 C.java
 Ashok.java

Case 2:

If class B declared as public and the program name is A.java then we will get compile time error saying “class B is
public should be declared in a file named B.java”

Case 3:

If we declare both A and B classes as public & name of the program is B.java then we will get compile time error
saying. “class A is public should be declared in a file named A.java”

class A {
public static void main(String[] args) {
System.out.println("A class main");
}
}

@Mragank Singhal P a g e |6
Unit - 1 Lecture Notes (Object Oriented Programming)
class B {
public static void main(String[] args) {
System.out.println("B class main");
}
}
class C {
public static void main(String[] args) {
System.out.println("C class main");
}
}
class D {
}

Save as Hello.java
Compile using: javac Hello.java
This will generate the following class files:
A.class
B.class
C.class
D.class
To execute the program:
java A
A class main method
java B
B class main method
java C
C class main method
java D
R.E: NoSuchMethodError: main
java Hello
R.E: NoClassDefFoundError: Ashok

 Whenever we are compiling a java program for every class present in the program a separate .class file will be
generated.
 Whenever we are executing a java class the corresponding class main method will be executed. If the class doesn’t
contain main method then we will get run time error saying NoSuchMethodError: main
 If the corresponding . class file not available then we will get RuntimeException saying NoClassDefFoundError
 It is not recommended to declare multiple classes in a single source file it is highly recommend to declare only one
class per source file and name of the program we have to keep same as class name. The main advantage of this
approach is readability and maintainability of the code will be improved.

@Mragank Singhal P a g e |7
Unit - 1 Lecture Notes (Object Oriented Programming)

Java Data Types and Variables


Java Is a Strongly Typed Language
Every variable has a type, every expression has a type, and every type is strictly defined. Second, all assignments,
whether explicit or via parameter passing in method calls, are checked for type compatibility. There are no
automatic coercions or conversions of conflicting types as in some languages. The Java compiler checks all
expressions and parameters to ensure that the types are compatible. Any type mismatches are errors that must be
corrected before the compiler will finish compiling the class.

The Primitive Types

Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. The primitive
types are also commonly referred to as simple types, and both terms will be used in this book. These can be put in
four groups:

 Integers This group includes byte, short, int, and long, which are for whole-valued signed numbers.
 Floating-point numbers This group includes float and double, which represent numbers with fractional
precision.
 Characters This group includes char, which represents symbols in a character set, like letters and numbers.
 Boolean This group includes boolean, which is a special type for representing true/false values.

Integers

Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java
does not support unsigned, positive only integers. The width and ranges of these integer types vary widely, as
shown in this table:

Name Width Range


long 64 bits (8 bytes) -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 bits (4 bytes) -2,147,483,64 to 2,147,483,64
short 16 bits (2 bytes) -32,768 to 32,767
byte 8 bits (1 byte) -128 to 127

Floating-Point Types

Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional
precision. For example, calculations such as square root, or transcendental such as sine and cosine, result in a value
whose precision requires a floating-point type. Java implements the standard (IEEE–754) set of floating-point types
and operators. There are two kinds of floating point types, float and double, which represent single- and double-
precision numbers, respectively. Their width and ranges are shown here:

@Mragank Singhal P a g e |8
Unit - 1 Lecture Notes (Object Oriented Programming)

Name Width Range


double 64 bits (8 bytes) 4.9e-324 to 1.8e+308
float 32 bits (4 bytes) 1.4e-045 to 3.4e+038

Characters

In Java, the data type used to store characters is char. A key point to understand is that Java uses Unicode to
represent characters. Unicode defines a fully international character set that can represent all of the characters
found in all human languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic,
Hebrew, Katakana, Hangul, and many more. At the time of Java’s creation, Unicode required 16 bits. Thus, in Java
char is a 16-bit type.

The range of a char is 0 to 65,536. There are no negative chars.

Boolean

Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true or
false. This is the type returned by all relational operators, as in the case of a < b. boolean is also the type required
by the conditional expressions that govern the control statements such as if and for.

Java Literals
A literal is a source code representation of a fixed value. They are represented directly in the code without any
computation.

Literals can be assigned to any primitive type variable. For example −

byte a = 68;
char a = 'A';

byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8) number
systems as well.

Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using these number systems for literals.
For example −

int decimal = 100;


int octal = 0144;
int hexa = 0x64;

String literals in Java are specified like they are in most other languages by enclosing a sequence of characters
between a pair of double quotes. Examples of string literals are −

@Mragank Singhal P a g e |9
Unit - 1 Lecture Notes (Object Oriented Programming)
Example

"Hello World"
"two\nlines"
"\"This is in quotes\""

String and char types of literals can contain any Unicode characters. For example −

char a = '\u0001';
String a = "\u0001";

Type Conversion and Casting


If the two types are compatible, then Java will perform the conversion automatically. For example, it is always
possible to assign an int value to a long variable. However, not all types are compatible, and thus, not all type
conversions are implicitly allowed. For instance, there is no automatic conversion defined from double to byte.
Fortunately, it is still possible to obtain a conversion between incompatible types. To do so, you must use a cast,
which performs an explicit conversion between incompatible types.

Automatic Conversion

When one type of data is assigned to another type of variable, an automatic type conversion will take place if the
following two conditions are met:

 The two types are compatible.


 The destination type is larger than the source type.

When these two conditions are met, a widening conversion takes place. For example, the int type is always large
enough to hold all valid byte values, so no explicit cast statement is required.

For widening conversions, the numeric types, including integer and floating point types, are compatible with each
other. However, there are no automatic conversions from the numeric types to char or boolean. Also, char and
boolean are not compatible with each other.

Casting Incompatible Types

Although the automatic type conversions are helpful, they will not fulfill all needs. For example, what if you want to
assign an int value to a byte variable? This conversion will not be performed automatically, because a byte is
smaller than an int. This kind of conversion is sometimes called a narrowing conversion, since you are explicitly
making the value narrower so that it will fit into the target type.

To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type
conversion. It has this general form:

(target-type) value

@Mragank Singhal P a g e | 10
Unit - 1 Lecture Notes (Object Oriented Programming)
Here, target-type specifies the desired type to convert the specified value to. For example, the following fragment
casts an int to a byte. If the integer’s value is larger than the range of a byte, it will be reduced modulo (the
remainder of an integer division by the) byte’s range.

int a;
byte b;
// …
b = (byte) a;

Type Promotion

Java defines several type promotion rules that apply to expressions. They are as follows: First, all byte, short, and
char values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted
to long. If one operand is a float, the entire expression is promoted to float. If any of the operands are double, the
result is double.

@Mragank Singhal P a g e | 11
Unit - 1 Lecture Notes (Object Oriented Programming)
Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be
created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer
a convenient means of grouping related information.

Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of
array the variable can reference. Here is the syntax for declaring an array variable −

Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.

Example

The following code snippets are examples of this syntax −


double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.

Creating Arrays

You can create an array by using the new operator with the following syntax −

arrayRefVar = new dataType[arraySize];

The above statement does two things −

 It creates an array using new dataType[arraySize].


 It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be
combined in one statement, as shown below −

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows −

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0
to arrayRefVar.length-1.

@Mragank Singhal P a g e | 12
Unit - 1 Lecture Notes (Object Oriented Programming)
Example

Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns
its reference to myList −

double[] myList = new double[10];

Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.

Processing Arrays

When processing array elements, we often use either for loop or foreach loop because all of the elements in an
array are of the same type and the size of the array is known.

Example
Here is a complete example showing how to create, initialize, and process arrays −

public class TestArray {


public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {

@Mragank Singhal P a g e | 13
Unit - 1 Lecture Notes (Object Oriented Programming)
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

This will produce the following result −

Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

The foreach Loops

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the
complete array sequentially without using an index variable.

Example

The following code displays all the elements in the array myList −

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}

@Mragank Singhal P a g e | 14

You might also like