OOPS Module I & II
OOPS Module I & II
System (OOPs)
What is OOPS?
• Object-Oriented Programming System (OOPs) is
a programming concept that works on the
principles of abstraction, encapsulation,
inheritance, and polymorphism.
• It allows users to create objects they want and
create methods to handle those objects.
• The basic concept of OOPs is to create objects,
re-use them throughout the program, and
manipulate these objects to get results.
List of OOPs Concepts in Java with
Examples
• The following are general OOPs concepts in Java:
– Class
– Object
– Encapsulation
– Inheritance
– Polymorphism
– Abstraction
– Association
– Aggregation
– Composition
Class
• The class is one of the Basic concepts of OOPs
which is a group of similar entities.
• It is only a logical component and not the
physical entity.
• If you had a class called “Expensive Cars” 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.
Object
• An object can be defined as an instance of a
class, and there can be multiple instances of a
class in a program.
• An Object is one of the Java OOPs concepts
which contains both the data and the function,
which operates on the data.
• For example - chair, bike, marker, pen, table,
car, etc.
Encapsulation
• Encapsulation is one of the best Java OOPs
concepts of wrapping the data and code.
• In this OOPs concept, the variables of a class
are always hidden from other classes.
• It can only be accessed using the methods of
their current class.
• For example - in school, a student cannot exist
without a class.
Inheritance
• Inheritance is one of the Basic Concepts of
OOPs in which one object acquires the
properties and behaviors of the parent object.
• It’s creating a parent-child relationship
between two classes.
• It offers robust and natural mechanism for
organizing and structure of any software
Polymorphism
• Polymorphism refers to one of the OOPs concepts
in Java which is the ability of a variable, object or
function to take on multiple forms.
• For example, in English, the verb run has a
different meaning if you use it with a laptop, a
foot race, and business.
• Here, we understand the meaning of run based
on the other words used along with it.
• The same also applied to Polymorphism.
Abstraction
• Abstraction is one of the OOP Concepts in Java
which is an act of representing essential features
without including background details.
• It is a technique of creating a new data type that
is suited for a specific application.
• Lets understand this one of the OOPs Concepts
with example, while driving a car, you do not
have to be concerned with its internal working.
• Here you just need to concern about parts like
steering wheel, Gears, accelerator, etc.
Association
• Association is a relationship between two
objects.
• It is one of the OOP Concepts in Java which
defines the diversity between objects.
• In this OOP concept, all object have their
separate lifecycle, and there is no owner.
• For example, many students can associate
with one teacher while one student can also
associate with multiple teachers.
Aggregation
• In this technique, all objects have their
separate lifecycle.
• However, there is ownership such that child
object can’t belong to another parent object.
• For example consider class/objects
department and teacher. Here, a single
teacher can’t belong to multiple departments,
but even if we delete the department, the
teacher object will never be destroyed.
Composition
• Composition is a specialized form of Aggregation.
• It is also called "death" relationship.
• Child objects do not have their lifecycle so when
parent object deletes all child object will also
delete automatically.
• For that, let’s take an example of House and
rooms. Any house can have several rooms. One
room can’t become part of two different houses.
So, if you delete the house room will also be
deleted.
Advantages of OOPs
• OOPs Concepts in Java offer easy to understand
and a clear modular structure for programs.
• Objects created for Object-Oriented Programs
can be reused in other programs. Thus it saves
significant development cost.
• Large programs are difficult to write, but if the
development and designing team follow OOPS
concepts, then they can better design with
minimum flaws.
• It enhances program modularity because every
object exists independently.
class First
{
public static void main(String args[])
{
System.out.println("Hello World");
int n;
n=25;
System.out.println(“Number=“ +n) ;
System.out.printf(Number=%d”, n);
n=n+10;
System.out.print(“New Number=“ ) ;
System.out.println(n) ;
}
}
The Primitive DataTypes
• 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.
Name Width in Bits Values
char 16
boolean Virtual Machine true/false(default)
Dependent
class Example {
public static void main(String args[])
{
char a = 'G';
int i = 89;
byte b = 4;
short s = 56;
double d = 4.355453532;
float f = 4.7333434f;
boolean k = true;
System.out.println("char: " + a);
System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println(“boolean: " + k);
}
}
Non-Primitive Data Type
• Non-primitive data types are called reference types because
they refer to objects.
• The main difference between primitive and non-primitive data
types are:
– Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and is not defined by Java (except for String).
– Non-primitive types can be used to call methods to perform certain operations,
while primitive types cannot.
– A primitive type has always a value, while non-primitive types can be null.
– A primitive type starts with a lowercase letter, while non-primitive types starts
with an uppercase letter.
– The size of a primitive type depends on the data type, while non-primitive types
have all the same size.
• Examples of non-primitive types are
– Strings,
– Arrays,
– Classes/Objects,
– Interface, etc.
String
class Example
{
public static void main(String args[])
{
String s = “Java";
String s1 = new String(“Java");
System.out.println(“String 1: " + s);
System.out.println(“String 2: " + s1);
}
}
Arrays
• One Dimensional Array
type var-name[ ];
array-var = new type [size];
int a[];
a = new int[5];
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
class Testarray3
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Multidimensional Arrays
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
Alternative Array Declaration Syntax
type[ ] var-name;
int a1[] = new int[3];
int[] a2 = new int[3];
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
Type Inference with Local
Variables
double avg = 10.0;
var avg = 10.0;
var k = 5;
var myArray = new int[10];
Operators
Arithmetic Operators
Bitwise Operators
Relational Operators
Boolean Logical Operators
Assignment Operator
var = expression;
X=100;
The ? Operator(Ternary/Conditional Operator)
expression1 ? expression2 : expression3
ratio = denom == 0 ? 0 : num / denom;
Operator Precedence
Control Statements
If
if (condition) statement1;
else statement2;
int a=5, b=7;
if(a < b) a = 0;
else b = 0;
if (condition)
{
statement1;
statement2;
}
else
{
statement3;
statement4;
}
int a=5, b=7;
if(a < b)
{
a = 0;
b = 10;
}
else
{
b = 0;
a = 10;
}
Nested ifs
The if-else-if Ladder
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
Switch
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN :
// statement sequence
break;
default:
// default statement sequence
}
• Nested switch
Iteration Statements
while
while(condition)
{
// body of loop
}
do-while
do
{
// body of loop
} while (condition);
for
for(initialization;condition;iteration)
{
//body
}
• Using the comma
int a, b;
for(a=1, b=5; a<b; a++,b--)
{
System.out.println(“a=“ +a “b=“ +b);
}
for loop variations
boolean done = false;
for(int i=1; !done; i++)
{
System.out.println(“Value:” + i);
if(i==10)
done = true;
}
for loop variations
boolean done = false;
int i=1;
for( ; !done; )
{
System.out.println(“Value:” + i);
if(i==10)
done = true;
i++;
}
for loop variations
for( ; ; )
{
//……
}
The For-Each Version of the for Loop
for(type itr-var : collection) statement-block
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int i=0; i < 10; i++)
sum = sum + nums[i];
------------------------------------------------------------
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
sum = sum + x;
Jump Statements
• break
• continue
• return
Class and Objects
• Class defines a new data type.
• This new type can be used to create objects of
that type.
• A class is a template for an object, and an
object is an instance of a class.
General Form of a Class
class name
{
type instance variable1;
type instance variable2;
.
.
.
type methodnameN(parameter-list)
{
Body of the method
}
}
Object Declaration
classname class-var;
class-var = new classname ( );
int compute()
{
return length*breadth;
}
}
class Demo
{
public static void main(String args[])
{
Shape rect = new Shape();
int a;
a = rect.compute();
System.out.println(“Area= " + a);
}
}
class Shape
{
int length;
int breadth;
Shape(int l, int b)
{
length = l;
breadth = b;
}
int compute()
{
return length*breadth;
}
}
class Demo
{
public static void main(String args[])
{
Shape rect = new Shape(10, 5);
int a;
a = rect.compute();
System.out.println(“Area= " + a);
}
}
The this Keyword
• A method will need to refer to the object that invoked
it.
• ‘this’ can be used inside any method to refer to the
current object.
• ‘this’ is always a reference to the object on which the
method was invoked.
void Shape()
{
this.length = 10;
this.breadth = 5;
}
Input Output Operations
Standard I/O Streams
Standard I/O Streams
• System.in: This is the standard input stream that is
used to read characters from the keyboard or any
other standard input device.
• System.out: This is the standard output stream that is
used to produce the result of a program on an output
device like the computer screen.Here is a list of the
various print functions that we use to output
statements:
• System.err: This is the standard error stream that is
used to output all the error data that a program might
throw, on a computer screen or any standard output
device.
InputStream Classes
OutputStream Classes
Primary Classes of Streams
• Input Stream: These streams are used to read
data that must be taken as an input from a source
array or file or any peripheral device. For eg.,
F i l e I n p u t S t r e a m , B u f fe r e d I n p u t S t r e a m ,
ByteArrayInputStream etc.
• Output Stream: These streams are used to write
data as outputs into an array or file or any output
peripheral device. For eg., FileOutputStream,
BufferedOutputStream, ByteArrayOutputStream
etc.
Stream Classification
ByteStream
• This is used to process data byte by byte (8
bits).
• T h o u g h i t h a s m a n y c l a s s e s , t h e
FileInputStream and the FileOutputStream are
the most popular ones.
• The FileInputStream is used to read from the
source and FileOutputStream is used to write
to the destination.
Byte Stream class Description
• BufferedInputStream: It is used for Buffered Input Stream.
• DataInputStream : It contains method for reading java standard
datatypes.
• FileInputStream: This is used to reads from a file.
• InputStream: This is an abstract class that describes stream input.
• PrintStream: This contains the most used print() and println()
method.
• BufferedOutputStream: This is used for Buffered Output Stream.
• DataOutputStream: This contains method for writing java standard
data types.
• FileOutputStream:This is used to write to a file.
• OutputStream:This is an abstract class that describe stream output.
CharacterStream:
• In Java, characters are stored using Unicode
conventions.
• Character stream automatically allows us to
read/write data character by character.
• Though it has many classes, the FileReader
and the FileWriter are the most popular ones.
• FileReader and FileWriter are character
streams used to read from the source and
write to the destination respectively.
Character Stream class Description
• BufferedReader: It is used to handle buffered input stream.
• FileReader:This is an input stream that reads from file.
• InputStreamReader: This input stream is used to translate
byte to character.
• OutputStreamReader: This output stream is used to
translate character to byte.
• Reader: This is an abstract class that define character
stream input.
• PrintWriter: This contains the most used print() and
println() method.
• Writer: This is an abstract class that define character stream
output.
• BufferedWriter: This is used to handle buffered output
stream.
• FileWriter: This is used to output stream that writes to file.
public class Main
{
public static void main(String args[]) throws java.io.IOException
{
int ch;
System.out.println("Enter the character to be displayed : ");
ch = System.in.read();
System.out.println("You entered : " + (char)ch);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the input string");
String name = in.readLine();
System.out.println("You entered: " + name);
}
}
import java.util.Scanner;
class Input
{
public static void main(String[] args)
{
Scanner a = new Scanner(System.in);
System.out.print("Enter first integer: ");
int x = a.nextInt();
System.out.print("Enter second integer: ");
int y = a.nextInt();
int z = x + y;
System.out.println(“Sum=" + z);
}
}
import java.util.Scanner;
class Input
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter float: ");
float myFloat = input.nextFloat();
System.out.println("Float entered = " + myFloat);
}
}
import java.util.Scanner;
class Input
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter double: ");
double myDouble = input.nextDouble();
System.out.println("Double entered = " +
myDouble);
}
}
import java.util.Scanner;
class Input
{
public static void main(String[] args)
{
System.out.print("Enter first text: ");
String myString1 = input.next();
System.out.print("Enter second text: ");
String myString2 = input.nextLine();
System.out.println("Text entered = " +
myString1 + myString2);
}
}
Overloading Methods
• In Java, it is possible to define two or more methods within the
same class that share the same name, as long as their parameter
declarations are different.
• The methods are said to be overloaded, and the process is referred
to as method overloading.
• Method overloading is one of the ways that Java supports
polymorphism.
• When an overloaded method is invoked, Java uses the type and/or
number of arguments as its guide to determine which version of the
overloaded method to actually call.
• Thus, overloaded methods must differ in the type and/or number of
their parameters.
• The overloaded methods may have different return types, the
return type alone is insufficient to distinguish two versions of a
method.
• When encounters a call to an overloaded method, it simply
executes the version of the method whose parameters match the
arguments used in the call.
class Test{
int a, b;
float x, y;
void compute() {
System.out.println(“No parameters");
}
void compute(int m) {
a=10;
b=m;
System.out.println(a*b);
}
void compute(int m, int n){
a=m;
b=n;
System.out.println(a*b);
}
void compute(float p) {
x=10;
y=p;
System.out.println(x*y);
}
float compute(float p, float q){
return p*q;
}
}
class Demo
{
public static void main(String args[])
{
Test obj = new Test();
float k
obj.compute();
obj.compute(5);
obj.compute(20, 50);
obj.compute(35.8);
k = obj.compute(24.2, 13.6);
System.out.println(k);
}
}
Automatic Type Conversion
class Test{
void compute(int x, int y) {
System.out.println(x*y);
}
void compute(double m) {
System.out.println(m);
}
class Demo
{
public static void main(String args[])
{
Test obj = new Test();
int k =15;
obj.compute(10,20);
obj.compute(k);
obj.compute(25.57,);
}
}
Overloading Constructors
class Shape
{
int length;
int breadth;
Shape()
{
length = 1;
breadth = 1;
}
Shape(int l, int b)
{
length = l;
breadth = b;
}
Shape(int k)
{
length = k;
breadth = k;
}
int compute()
{
return length*breadth;
}
}
class Demo
{
public static void main(String args[])
{
Shape ob1 = new Shape();
Shape ob2 = new Shape(10, 15);
Shape ob3 = new Shape(5);
int a;
a = ob1.compute();
System.out.println(“Area= " + a);
a = ob2.compute();
System.out.println(“Area= " + a);
a = ob3.compute();
System.out.println(“Area= " + a);
}
}
Objects as Parameters
class ObjectPassDemo
{
int a, b;
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}
boolean equalTo(ObjectPassDemo o)
{
return (o.a == a && o.b == b);
}
}
public class Test
{
public static void main(String args[])
{
ObjectPassDemo ob1 = new ObjectPassDemo(100,
22);
ObjectPassDemo ob2 = new ObjectPassDemo(100,
22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
System.out.println("ob1 == ob2: " +
ob1.equalTo(ob2));
System.out.println("ob1 == ob3: " +
ob1.equalTo(ob3));
}
}
class Box
{
double width, height, depth;
Box(Box ob)
{
width = ob.width;
height = ob.height;
depth = ob.depth;
}
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
double volume()
{
return width * height * depth;
}
}
public class Test
{
public static void main(String args[])
{
Box mybox = new Box(10, 20, 15);
Box myclone = new Box(mybox);
double vol;
vol = mybox.volume();
System.out.println("Volume of mybox is " + vol);
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
}
}
Returning Objects
class Test
{
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
}
class Retob
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
}
}
Recursion
Access Control