CS8392 OBJECT ORIENTED PROGRAMMING Unit1

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 221

Mrs.

J GNANA JESLIN,
CS8392 -OBJECT ORIENTED
PROGRAMMING
• UNIT-1   INTRODUCTION TO OOP AND JAVA
FUNDAMENTALS
• UNIT -2  INHERITANCE AND INTERFACES

• UNIT-3 EXCEPTION HANDLING AND I/O

• UNIT-4 MULTITHREADING AND GENERIC


PROGRAMMING
• UNIT-5 EVENT DRIVEN PROGRAMMING 
Text Books
1. Herbert Schildt, “Java The complete
reference”, 8th Edition, McGraw Hill
Education, 2011.
2. Cay S. Horstmann, Gary cornell,
“Core Java Volume –I
Fundamentals”, 9th Edition, Prentice
Hall, 2013.
REFERENCES

1. Paul Deitel, Harvey Deitel, “Java SE 8 for


programmers”, 3rd Edition, Pearson, 2015.
2. Steven Holzner, “Java 2 Black book”, Dreamtech
press, 2011.
3. Timothy Budd, “Understanding Object-oriented
programming with Java”, Updated Edition,
Pearson Education, 2000.
REFERENCES

1. https://www.tutorialspoint.com/java/index.h
tm
2. https://www.javatpoint.com/java-tutorial
3. https://www.w3schools.com/java/
4. https://www.geeksforgeeks.org/java-
tutorial/
5. https://docs.oracle.com/javase/tutorial/
UNIT - I
INTRODUCTION TO OOP
AND JAVA
FUNDAMENTALS
Object Oriented Programming – Abstraction – objects and
classes – Encapsulation- Inheritance – Polymorphism-
OOP in Java – Characteristics of Java – The Java Environment
– Java Source File Structure – Compilation.
Fundamental Programming Structures in Java – Defining
classes in Java – constructors, methods -access specifiers –
static members -Comments, Data Types, Variables,
Operators, Control Flow, Arrays , Packages – JavaDoc
comments.
S TOPIC
NO
1 Object Oriented Programming-Abstraction–objects and
classes-Encapsulation-Inheritance-Polymorphism
2 Characteristics of Java –The Java Environment -Java Source
File -Structure –Compilation. Java –Data Types, Variables,
Operators
3 Control Flow, Arrays , Methods
4 Defining classes in Java, constructors,
5 Access specifiers -Static members ,
6 Packages –Java Doc comments.
Introduction to Programming
Concepts
Human Language
•  Commonly used to express feelings and
understand other person expressions.
• It can be oral or gestural kind of
communication
Human Language
Computer Language:
•  Computer languages are the languages by
which a user command a computer to work
on the algorithm which a user has written to
get an output.
COMPUTER PROGRAM

PROGRAMMING LANGUAGE
LEVELS OF PROGRAMMING
LANGUAGE
C –PROGRAM JAVA PROGRAM

#include<stdio.h> import java.io.*


class First
void main() {
{ public static void main(String args[])
printf(“hello “); {
} System.out.println(“Let’s do something with java”);
}
}
Execution of Java Program
• https://www.oracle.com/java/technologies/ja
vase-downloads.html

• https://www.eclipse.org/downloads/
Online compilers

• https://www.codechef.com/ide
• https://www.onlinegdb.com/online_java_com
piler
• https://www.tutorialspoint.com/compile_java
_online.php
• https://compiler.javatpoint.com/opr/online-
java-compiler.jsp
PROGRAMMING PARADIGMS
Main Program

Data
– Unstructured Programming

– Procedural programming

• Structured programming

– Modular programming

– Object-oriented programming
OBJECT ORIENTED PROGRAMMING
• Object Oriented Programming is a
Methodology or Paradigm to design a
Program/Software application based on
objects.
• Objects are real-world entity.
• Any things we see, that could be
differentiated from another is called object.
Object-Orientation
• It is a kind of thinking methodology
– Everything in the world is an object;
– Any system is composed of objects (certainly
a system is also an object);
– The evolution and development of a system is
caused by the interactions among the objects
inside or outside the system
Everything in the world is an object
• A flower, a tree, an animal
• A student, a professor
• A desk, a chair, a classroom, a building
• A university, a city, a country
• The world, the universe
• A subject such as CS, IS, Math, History, …
Any system is composed of objects
• A law system
• A cultural system
• An educational system
• An economic system
• An Information system
• A computer system
Object Oriented Programming
Features

• Object
• Class
• Inheritance
• Polymorphism
•Abstraction
•Encapsulation
OBJECT ORIENTED PROGRAMMING
 Program is composed of a collection of individual
units, or objects, as opposed to a traditional view
in which a program is a list of instructions to
the computer
Object B

Data variable
Object A Object C
Member Function
Data variable Data variable

Member Function Member Function


Object1
Data1+Procedures1

Object2

Data
Data2 + Procedures
Data12
Object3
Data3 + Procedures3

Object4

Data4 + Procedures4
OBJECTS

• The smallest logical unit of Java is the object

• Objects are identified by its unique name.

• An object is a instance of a class.

• Objects are the basic runtime entities in an


object oriented system.
• Real-world objects share two characteristics:
They all have state and behavior.
• Dogs have state (name, color, breed, hungry)
and behavior (barking, fetching, wagging tail).
• Software objects also have a state and
behaviour.
• A software object's state is stored in fields and
behaviour is shown via methods.
Declaring and creating objects
• An object in JAVA is essentially a block of memory
that contains space to store all the instance
variables
•  Creating an object also refers to INSTANTIATING
AN OBJECT.
• Objects in JAVA are created using new keyword.
• The new operator dynamically allocates memory
for an object.
Declaring and creating objects
Declaring and creating objects
Bundling code into individual software
objects provides a number of benefits

• Modularity
• Information-hiding
• Code re-use
• Pluggability and debugging ease
CLASSES
 A class is the blueprint from which individual
objects are created.
 Classes are made up of objects.
• A class is a group of objects which have
common properties.
• It is a logical entity. It can't be physical.
• Class doesn't consume any space, Objects do.
DECLARING A CLASS
• A class must have a valid identifier name; it can begin with
an alphabetic character, the underscore, or the dollar sign.

• Syntax for declaring a class:

• The class body is declared within curly braces.

class MyClass {
member variables;

member functions () ;

} // end class MyClass
Example : Objects and Classes

object class
class Student
char name
int rollNo
setName()
setRollNo()
calcMarks()
Jodie Daria Jane Brittany
R001 R002 R003 R004
ABSTRACTION
Is the act of representing the essential features
ignoring the background details.
Abstraction means ignoring irrelevant features,
properties, or functions and emphasizing the
relevant ones...
“Relevant” to what?

... relevant to the given project (with an


eye to future reuse in similar projects).
•For example a car, the user sees a car as a car rather
than its individual components.
•In Java, Abstraction is achieved by abstract class and
interface.
ENCAPSULATION
• Encapsulation is a process of wrapping of data
and methods in a single unit is called
encapsulation.
• Encapsulation is achieved in java language by
class concept.
• Combining of state and behaviour in a single
container is known as encapsulation.
ENCAPSULATION
Advantage of Encapsulation
The main advantage of using of encapsulation is to secure the
data from other methods, when we make a data private then
these data only use within the class, but these data not accessible
outside the class.
INHERITANCE

•A class can extend another class, inheriting all


its data members and methods while
redefining some of them and/or adding its
own.
•Inheritance represents the is a relationship
between data types.
•For example: a FemaleDancer is a Dancer.
Inheritance Terminology:

subclass superclass
or extends or
derived class base class

public class FemaleDancer extends Dancer


{
...
}
Types Of Inheritance – supported by Java
Inheritance
Person

Student Faculty Staff


Base class-->Employee
class Employee
{
String name;
double salary;
public void raise(double dd)
{
salary += salary * dd/100;
}
public Employee ( … ) { … }
}
Derived class-->Manager
class Manager extends Employee
{
private double bonus;
public void setBonus(double bb)
{
bonus = salary * bb/100;
}
public Manager ( … ) { … }
}
POLYMORPHISM

•Means the ability to take more than one form.

•polymorphism refers to a programming language's


ability to process objects differently depending on
their data type or class.

•More specifically, it is the ability to redefine


methods for derived classes.
• Polymorphism

PRINT TEXT object


30000

PRINT
25000
20000

GRAPH object 15000


10000
B L UE S K Y…
5000
0
North South East West

PRINT IMAGE object


• Polymorphism in Java has two types:
– Compile time polymorphism (static binding)
and
– Runtime polymorphism (dynamic binding).
– Method overloading is an example of static
polymorphism
– method overriding is an example of
dynamic polymorphism.
Static Polymorphism
• In Java, static polymorphism is achieved
through method overloading.
• Method overloading means there are several
methods present in a class having the same
name but different types/number of
parameters.
Dynamic Polymorphism
• Dynamic polymorphism is achieved by method
overriding
• Declaring a method in sub class which is already
present in parent class is known as method
overriding. 
• Same method is overridden with same signature
in different classes.
• Suppose a subclass overrides a particular method
of the superclass.
Top Mobile & Web Applications of
Java in Real World
• Spotify (Music Streaming App) ...
• Twitter (Social Media App) ...
• Opera Mini (Web Browser) ...
• Nimbuzz Messenger (Instant Messaging App)
• CashApp (Mobile Payment Service) ...
• ThinkFree Office (Desktop-based App) ...
• Signal (Encrypted Messaging Services) ...
• Murex (Trading System)
JAVA - HISTORY
Characteristics of Java
Characteristics of Java
The Java Environment
The Java Environment
Java Environment / Java Architecture
• Java programs can typically be developed in
five stages:
– Step 1:Edit
– Step 2: Compile -Javac
– Step 3: Loading
– Step 4:Verify
– Step 5: Execute - JVM
The Java Environment
JDK
API
JVM
COMPILATION OF JAVA
PROGRAM
Java Language Fundamentals
• Keywords
• Data Types
• Variables
• Operators
• Conditional Statements
• Loops
Keywords In Java
• Java keywords are also known as reserved
words.
• Keywords are particular words that act as a
key to a code.
• These are predefined words by Java so they
cannot be used as a variable or object name
or class name.
DATA TYPES
• Data can be given certain names in the
program, these names are called variables.
• These variables point to a memory location
where the value is stored.
• This value can change during the program run.
• The type of data stored by a variable is
represented using data types.
TYPES OF VARIABLES
SIMPLE IF
IF ELSE
IF ELSE IF LADDER
NESTED IF
SWITCH
LOOPS / ITERATIONS
WHILE
DO WHILE
FOR
JUMP STATEMENTS
BREAK
CONTINUE
RETURN
CONSTRUCTORS
• A constructor is a method which is invoked when an
object of a class is created.
• A class can have more than one constructor.
• A constructor is always called by new operator.
• Types of constructor:
– Default constructor.
– Parameterized constructor.
• General form of a constructor
[access-specifier] class name (arguments)
{
Statements;
}
Characteristics of a constructor:
• It has the same name as the class.
• A class can have more than one constructor.
• It can take zero, one or more parameters.
• It has no return value.
• It can be overloaded.
• It is always called with new operator.
Functions of a constructor:
• It can be used to initialize the fields.
• It allocates memory space too the fields
E.G.: Constructor
import java.io.*;
class add
{
int a=0;
int b=0;
int c;
add(int n1,int n2)
{
System.out.println("Parameterized constructor");
a=n1;
b=n2;
}
add()
{
System.out.println("Default constructor");
}
void addnum()
{
c=a+b;
}
void print()
{
System.out.println("value of A="+a);
System.out.println("value of B="+b);
System.out.println("Sum="+c);
}
}
class add1{
public static void main(String args[]){
add A=new add(10,20);
A.addnum();
A.print();
add B=new add();
}
}
METHODS
• Methods are declared inside the body of
the class and after the declaration of
instance variables.
• Methods can receive arguments and return a
value.
• Objects without any method do not respond
to any message.
• Method which does not return any value is
declared as void.
General form of defining method:

<access specifier>[return_Type]
methodname(parameter list)
{
Statements;
[return value]
}
Method declaration have four basic parts:
1) Method name
2) Return type
3) Parameter list
4) Body of the method
Types of methods
• Based on the processing of fields methods are divided into
two categories:

– Mutators
» Methods that change field values of an object
are called mutator methods.

e.g: add(int n1,int n2)


{
a=n1;
b=n2;
}
– Accessors
» Methods that only access fields of an
object without modifying them.
E.G:
public int number()
{
return n1;
}
METHOD PARAMETERS
• Parameters are also called as arguments.
• These are the data required for a method to do
the process.
• The java always uses call by value to call
methods.
• There are two types of parameters available in
java
– Primitive types.
– Object references
“this” keyword
• “ this” can be used inside any method to refer
the current object.
• “this “ is always a reference to the object on
which the method is invoked.
EXAMPLE:
class point
{
Int x,y;
Void init(int x,int y)
{
this.x=x;
this.y=y;
}
CREATING OBJECTS
Creating an object is also referred as instantiating
an object.
Objects in java are created using new operator
New operator creates an object of the specified
class and returns the reference to that object.
Eg:
Rectangle rect1; //declare
Rect1 = new rectangle(); //instantiate
(or)
Rectangle rect1 = new rectangle();
OBJECTS
• We can create any number of objects for the
rectangle class.
Eg:
Rectangle rect1 = new rectangle();
Rectangle rect2 = new rectangle();
• Each object has its own copy of the member
variables of its class.
• Any changes to the variables of one object will
not affect the variables of another objects.
• Key Characteristics of an object:
– Identity
• The name to identify the object uniquely among
multiple objects.
—Behavior
• The processes that can be done on fields by the
objects.(methods)
—State
• The changes in data after processing or
initialization.(Fields)
Characteristics Of A Object
• Object is a block of memory that contains
space to store all instance variables.
• Once a class has been defined any number of
objects can be created in that class.
• Each object is allocated a separate storage
block.
• Objects can be created as an array.
ACCESSING MEMBERS
• Accessing fields:
– Fields can be accessed by the methods of its own class.
– The methods of other class needs object to access the
fields.
• General form
• Object_name.field_name;
– Eg:a.num1;

• Generally fields are accessed for two purpose


– To change the value of the field.
– To use the value of the field in an expression or
statement.
• Accessing methods:
– Methods of a class can be accessed by the methods
of its own class.
– The methods of other class needs object to access
the methods.
• General form
• Object_name.method_name(parameters);
– Eg:a.num(10,20);

• Generally methods are accessed for two purpose


– To change the value of the field.
– To get a value after a particular process is done by
fields.
ACCESS SPECIFIERS
• Access specifiers are used to enable or restrict
access to the members of a class from outside.
• It is also known as visibility modifiers.
• Java offers four access specifiers, listed below
in decreasing accessibility:
• public
• protected
• default (no specifier)
• private
PUBLIC SPECIFIER
• public classes, methods, and fields can be
accessed from everywhere.
• The only constraint is that a file with Java
source code can only contain one public class
whose name must also match with the
filename.
• Public members are accessible to its own
package and other packages.
• This is the lowest level of protection.
PROTECTED SPECIFIER
• protected methods and fields can only be
accessed within the same class to which the
methods and fields belong, within its
subclasses, and within classes of the same
package, but not from anywhere else.
• This protection lies between private and
public.
• Classes and subclasses in the other package
cannot access protected members.
DEFAULT SPECIFIER(NO SPECIFIER)
• If you do not set access to specific level, then
such a class, method, or field will be accessible
from inside the same package to which the
class, method, or field belongs, but not from
outside this package.

• This access-level is convenient if you are


creating packages.
PRIVATE SPECIFIER
• Private methods and fields can only be accessed
within the same class to which the methods
and fields belong.
• private methods and fields are not visible within
subclasses and are not inherited by subclasses.
• So, the private access specifier is opposite to the
public access specifier. It is mostly used for
encapsulation: data are hidden within the class.
• Private methods act like final methods. (i.e. it
cannot be inherited by the subclass)
STATIC MEMBERS
• Static members are contained within a class
and can be accessed without creating an
instance of a class.(i.e. object)

• The following can be declared as static.

• Fields.
• Constants.
• Methods.
import java.io.*;
class circle
{
static int r=2; // static field
static double a;
static final double pi=3.14; //static constant
static double area() //static method
{
a=pi*r*r;
return a;
}
}
class area
{
public static void main(String args[])
{
System.out.println("the value of pi="+circle.pi);
System.out.println("the value of
radius="+circle.r);
System.out.println("the value of
area="+circle.area());
}
}
PACKAGES
• Way to group a related class and interface into
one unit.
• Packages are essentially a means of organizing
classes together as groups.
• Package declaration
– The first statement, other than comments, in a Java
source file, must be the package declaration.
– Syntax
• package packagename;
– E.g.:
• package area;
• While creating a package, care should be taken that the
statement for creating a package must be written before any
other import statements

LEGAL ILLEGAL

package mypackage ; import java.io;


import java.io; package mypackage ;
In Java, the Packages can be imported into a program in the
following manner :
import <package_name>.<class_name>;
Suppose we wish to use a class say MyClass whose location is as
follows :

mypackage mysubpackage MyClass

– import mypackage.mysubpackage.MyClass;
Two ways to import a package
Importing a specific Package Member

• import mypackage.Calculator;
Importing an Entire Package

• import mypackage.*;
Package statement should be the
package mypackage; first statement. It is optional
import java.awt.*;
import java.uti.*;

class MyClass{
//attributes and functions import statements are optional.
} There can be any no of import
public class Demo{ statements.
//attributes and functions
}

Any no of classes and interfaces


but there can be only one public
class in a given .java file
• A class can use all classes from its own
package and all public classes from other
package.
• In packages one can import the specific class
or the whole package.

• Syntax for accessing packages:


– Import Package_name.class_name;
• E.g
– import area.square;
• Standard java packages
– Java.lang Language support classes.(int,float)
– Java.util Language utility classes.(date)
– Java.net Classes for networking.
– Java.awt classes for implementing GUI.
– Java.applet classes for creating and implementing
applets.
Advantages of packages:
• Classes can be easily reused.
• Two classes in different package can have the
same name.
• Packages provide a way to hide classes.
• Comments are used to clear the logic of the code and
to increase the readability of it.
• Comments are ignored by the compiler.
• Java uses three types of comments:
– Single-line comment(//). Example:
//single-line comment here
– Multiple-line comment(/*…*/). Example:
/*
line 1 here
line 2 here …
*/
– Documentation comment(/**…**/). It is multiple-line and
used with “javadoc” utility to create application
documentation.
• Javadoc:
– Is a tool to generate HTML documentation from
java code.
• Input: Java source files (.java)
– Individual source files
– Root directory of the source files
• Output: HTML files documenting specification
of java code
– One file for each class defined
– Package and overview files
• Comments can be inserted for the following
things.
• Packages
• Public classes and interfaces.
• Public and protected methods.
• Public and protected fields.
• Types of comments:
– Class comments
– Method comments
– Field comments
– Package and overview comments
• Class comments:
– It is placed after import all statements and before the
class definition.
import java.io.*;
– @author name: /** class comments should
• Adds entry about author. be written here **/
public class area
– @version text {
• Description about current version. …………………
}
– @since text
• Earlier version details.
– @deprecated text
• Adds description about the class, variable or method that should
not be used.
– @see reference
• Hyperlink added in the see also section
• Method comments:
– It is defined immediately before the method that it
describes.
/** adding two no’s.
@param variable description @param a&b are two no’s to be added
@return result of addition
– Describes method parameter. **/
public int add(int a, int b)
{
int c=a+b;
@return description return c;
• Describes return }

value of method.

@throws class description


– Describes method that throws exception
• Field comments:
– Adds description to public fields with static constants.

/**
*value of pi
**/

Public static final double pi=3.147;


• An array is a data structure that stores a
collection of values of same data type.
• An array has a fixed:
• Name
• Type
• Length
• Array types
• One dimensional array.
• Two dimensional array.
• One dimensional array:
– Is a list of elements of the same data type.
• Declaring an array:
– An array variable is declared by specifying the
array data type, followed by[] and the array
variable name.
• General form:
– Data_type arrayname[];
Or
– Data_type[] arrayname;
• E.g.:
– int a[];
• Creating array
– An array is created by allocating memory space to the
arrays (i.e. new operator is used).
– Array_name=new data_type[size];(Size is the number of elements in an array)
– a=new int[10];
– Array declaration and creation can be combined as
one statement as follows:
• int a[]=new int[10];
• Accessing the elements of an array:
– Each item in an array is called an element.
– Each element is accessed by numerical index within[].
– All array index starts with zero and ends with
(array.lenth-1).
– Array_name[<index>]
• Array initializers:
– Array elements are initialized explicitly using loop.
– It can also be initialized while array creation.
– General form
• <data_type> arrayname[]={<values list>}
– E.g
– int a[]={1,2,3,4,5}
Or
– for(int i=1;i<=5;i++)
{
a[i]=i;
}
• Anonymous arrays
– Allocates a new array and fills it with values inside
the braces.
– General form
• New <data_type>[]{<list of values>};
– E.g
• a=new int[]{1,2,3,4,5};
• Array size:
– The number of elements in an array can be found
using array_name.length
– E.g
• a.length=4
• Copying arrays:
– One array variable can be copied into another
variable.
e.g.:
Class array1
{
Public static void main(String args[])
{
int a[]={1,2,3,4,5};
int b[]={10,20,30,40,50};
b=a;
for(int i=0;i<b.length;i++)
{
System.out.println(i+“:”+b[i]);
}} }
• Using arraycopy() method:

– The system class has an arraycopy() method which


can be used to copy data's from one array to
another array.
– Arraycopy(object from, int from index, object to,
int to index, int count)
– E.G: (a,2,b,3,4)
import java.util.*;
import java.io.*;
class array1
{
public static void main(String args[])
{
int a[]={1,2,3,4,5,6};
int b[]={10,20,30,40,50,60,70,80,90};
System.arraycopy(a,2,b,3,4);
for(int i=0;i<b.length;i++)
{
System.out.println(""+b[i]);
}
}
}
• Command Line parameters:
– Every java program has a main method with a
string args[] parameter.
– This parameter indicates that the main method
receives an array of strings, namely, the
arguments specified on the command line.
– While running the program any things written
after the name of the class are the command line
arguments.
import java.util.*;
import java.io.*;
class array1
{
public static void main(String args[])
{
if(args[0].equals("h"))
System.out.println("hello");
else if(args[0].equals("g"))
System.out.println("hello world");
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
• Sorting an array:
– The array class has the sort array method that can
be used to sort the array of numbers.
– Various methods of java.util.array class

»Static void sort(a[])


»Static int search(a[],key)
»Static boolean equals(int a[],int b[])
»Static void fill(a[],val)
import java.util.*;
import java.io.*;
class array1
{
public static void main(String args[])
{
int a[]={5,6,1,8,2};
System.out.println("The unsorted array");
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
Arrays.sort(a);
System.out.println("The sorted array");
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
• Multidimensional array:
– Is an array which has more than one index to access
the elements.
– Syntax
• Declaration:
<data_type> array_name[][][];
• E.g: int a[][][];
• Creation:
array_name=new <data_type>[size1][size2];
• E.g: a=new int[3][3][3];
• int a[][][]=new int[3][3][3];
import java.util.*;
import java.io.*;
class array1
{
public static void main(String args[])
{
int a[][]=new int[3][5];
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
a[i][j]=i;
System.out.print(""+a[i][j]);
}
System.out.println("");
}
}
}
RAGGED ARRAYS
•Ragged arrays have rows of unequal length
•each row has a different number of columns, or entries

•Ragged arrays are allowed in Java

•Example: create a 2-D int array named b with 5 elements in


the first row, 7 in the second row, and 4 in the third row:
int[][] b = new int[3][];
b[0] = new int[5];
b[1] = new int[7];
b[2] = new int[4];
THANK YOU….

You might also like