Вы находитесь на странице: 1из 87

by

Santanu Basak
Dept. Of CSE, UEM, Jaipur
Introduction
Introduction

The focus of procedural programming is to


break down a programming task into a
collection of variables, data structures, and
subroutines.
Introduction

Modular programming
It is the process of subdividing a computer
program into separate sub-programs.
A module is a separate software component.
Introduction

Top-Down
In Top-Down development we start out with
your main function and then think of the main
steps you need to take, then you break up each
of those steps into their subparts and so on.
Introduction

Bottom-Up
In Bottom-Up programming you think of the
basic functionality and the parts you're going to
need and build them up.

You develop the actors and their methods and


then you tie them together to make a coherent
whole.
Introduction

OOP naturally tends toward Bottom-Up as


you develop your objects, while procedural
programming tends toward Top-Down as
you start out with one function and slowly
add to it.

Structured programming
Introduction

Structured programming failed for


bug-free
maintain
reusable
Object Oriented Paradigm

major objectives is to eliminate some


disadvantages of procedural languages

OOP ties data more closely to the functions


that operate on it and protects it from
unintentional modification by other
functions.
Object oriented programming Language

Smalltalk
Objective C
C++ (an extension of C language) -
procedural language with object oriented
extension
Features of object oriented paradigm

Data is hidden and cannot be accessed by


external functions.
Object may communicate with each others
through methods
New data or method can be added when they
are required
Object oriented programming is an approach
that provides a way of modularizing programs
by creating partitioned area for both data and
functions that can be used as templates for
creating copies of such modules on demand.
BASIC CONCEPT OF OOPS (OBJECT-ORIENTED
PROGRAMMING)

Class
User-defined data types.
BASIC CONCEPT OF OOPS (OBJECT-ORIENTED
PROGRAMMING)

Object
a person, a place, a bank account.
It takes some space in memory.
When a program is executed, the objects interact by sending
messages to one another.
A customer object sending request for getting balance to
account object.
Each object contains data and code to manipulate the data.
An object can interact without knowing the details of each
others data or code.
It is sufficient to know the types of message accepted and the
type of response returned by the object.
Object is like a black box
BASIC CONCEPT OF OOPS (OBJECT-ORIENTED
PROGRAMMING)

Abstraction : ATM
One level : using valid ATM card we can
make a transaction.
There are subsystems : a system that validate
the card, pin, balance
Get money.
Money come out.
So each of the parts has unique behavior and
each part can be updated easily.
BASIC CONCEPT OF OOPS (OBJECT-ORIENTED
PROGRAMMING)

Login module
Withdraw module
Change pin module
Cash transfer module
Mini-statement module

They are different from each others


BASIC CONCEPT OF OOPS (OBJECT-ORIENTED
PROGRAMMING)

Polymorphism
Encapsulation :
Inheritance
Data Encapsulation
wrapping of data and functions / methods
into a single unit
Basic of encapsulation is a class (contains
data and code)
Data Hiding
Data Hiding : Protect data from direct
access (access modifiers : public, protected,
private, default)
Comparison : Java vs C++
Sl.
No Java C++
1. True object oriented language C with object oriented language
2. Strictly object oriented Both procedural and object oriented
3. Does not support operator Support
overloading
4. Does not support pointer Support
5. Does not support global variable, Support
declare within class
6. Platform independent Platform dependent
7. Does not support multiple Support
inheritance for classes but supports
using interface
8. Java has finalize() method It has destructor
9. It is not a subset of C or C++ It is a superset of C
Java Features 1
Compiled and interpreted
Two stage system
Platform independent and portable
Code can be moved from one system to another
Object oriented
Almost everything is an object. Code and data exist in
object and classes
Robust and secure
Well made
Garbage collection
Exception handling
secure
Absence of pointer
Java Features 2
Distributed
Remote object can be accessed on internet
Developers can work from different location on
single task
Multithreaded
Managing multiple tasks simultaneously
One application does not need to wait for completion
of another
Extensible
Supports code of other language
Source code Execution

Java Source
Java Compiler Java Virtual Machine
Code javac java
Bytecode (.class) Machine code
(.java)
JVM

Bytecode Class Bytecode Machine


Interpreter
(.class) Loader verifier code
class in Java

class ClassName {
//class body
}
Method/s in Java
class MyClass {
void methodName(){
//method body
}
int methodName2(){
//method body
return 0;
}
float methodName3(float a){
//method body
return a;
}
}
Method calling in Java
class MyClass {
void test(){
class MyClass2 {
public static void main(String args[]){
//method body int i=0;
} float f=0f;
int test2(){ MyClass m1 = new MyClass();

//method body m1.test();


return 0; i=m1.test2();
} f=m1.test3(9f);
}
float test3(float a){
//method body }
return a;
}
}
main method in Java
class MyClass {
public static void main(String args[]){
//main body
}
}
Print in console
class MyClass {
public static void main(String args[]){
int a=10;
System.out.print(Java);
System.out.println(i);

}
}
Chapter 7
Types of Polymorphism

Polymorphism

Compiletime Runtime
Polymorphism Polymorphism
Static Binding Dynamic Binding
(Method Overloading,
(Method overriding)
Constructor Overloading)
Compiletime Polymorphism
Static Binding
Method Overloading
Constructor Overloading
Method Overloading
It is possible to define more than
one methods with same name in a
class
Methods share same name
No of parameter/s different
Types of parameter/s different
Method Overloading (Overload.java)
class OverloadDemo {
void test() {
System.out.println("No Parameters");
}

//overload test with one integer parameter


void test(int a) {
System.out.println("a : "+a);
}

//overload test with two integer parameter


void test(int a, int b) {
System.out.println("a & b "+a+" "+b);
}

//overload test with one double parameter


double test(double a) {
System.out.println("double : "+a);
return a*a;
}
}

class Overload {
public static void main(String args[]){
//create an instance for class OverloadDemo
OverloadDemo od=new OverloadDemo();

//call all test methods


od.test();
od.test(5);
od.test(2,3);
System.out.println("Result "+od.test(11.1));
}
}
Method Overloading (Overload2.java)
class OverloadDemo2 {
void test() {
System.out.println("No Parameters");
}

//overload test with two integer parameter


void test(int a, int b) {
System.out.println("a & b "+a+" "+b);
}

//overload test with one double parameter


double test(double a) {
System.out.println("double : "+a);
return a*a;
}
}

class Overload2 {
public static void main(String args[]){
//create an instance for class OverloadDemo
OverloadDemo2 od=new OverloadDemo2();

//call all test methods


od.test();
od.test(5);
od.test(2,3);
System.out.println("Result "+od.test(11.1));
}
}
Method Overloading
C language doesn't support
polymorphism
For same operation has to be
defined methods with different
names
C language : doesnt support polymorphism (same operation)
int addInt(int a, int b){
return a+b;
}
float addFloat(float a, float b){
return a+b;
}
double addDouble(double a, double b){
return a+b;
}
Java language : supports polymorphism
int add(int a, int b){
return a+b;
}
float add(float a, float b){
return a+b;
}
double add(double a, double b){
return a+b;
}
Automatic conversion
To resolve call if no matching method
found
integer can be converted into float, double
during method calling
float can be converted into double during
method calling
Method Overloading : Automatic conversion
class Cal {
double add(double a, double b){
return a+b;
}
}
class MyClass {
public static void main(String args[]){

Cal c=new Cal();

System.out.println(c.add(10, 20));
System.out.println(c.add(10f, 20f));
System.out.println(c.add(10.1d, 20.2d));
}
}
Constructor Overloading
Compiletime Polymorphism (static binding) (MyClass2.java)
class Cal { class MyClass {
int a,b; public static void main(String args[]){
Cal(){ int result;
a=0; //instance with default constructor
b=0; Cal c1=new Cal();
} result = c1.getResult();
Cal(int i, int j) { System.out.println(result);
a=i;
b=j; //instance with two parameter constructor
} Cal c2=new Cal(10,20);
int getResult() { result = c2.getResult();
return a+b; System.out.println(result);
} }
} }
Using Object As Parameter (MyClass3.java)

class Cal { class MyClass2 {


int a,b; public static void main(String args[]){
Cal(){ Cal c1=new Cal();
a=0;
Cal c2=new Cal(10,20);
b=0;
Cal c3=new Cal(10,20);
}
Cal(int i, int j) {
a=i; System.out.println(c1.equal(c2));
b=j; System.out.println(c2.equal(c3));
}
boolean equal(Cal c) { }
if(a==c.a && b==c.b) }
return true;
else
return false;
}
}
Returning Object (MyClass4.java)

class Cal { class MyClass2 {


int a; public static void main(String args[]){
Cal c2=new Cal(10);
Cal(int i) {
Cal c3;
a=i;
c3=c2.incr();
}
Cal incr() {
System.out.println(c3.a);
Cal c=new Cal(a+1); }
return c; }
}
}
Introducing Access Control
Encapsulation provides access control
Which part of code is accessible
Misuse is prevented
Allowing data access only through a method
Access Modifier
How a member can be accessed using
instance
How a member can be accessed after
inheritance
Access Modifiers in Java (Stack.java)
public
Member can be accessed by any other code
main () method is public
So JVM can access main() to start execution
Private
Member can be accessed by only the members
of same class
protected
Default
No modifier is defined
Understanding static
static member is accessed independently of
any object of that class (without creating an
instance member can be accessed)
static member can be accessed before creating
any instance of that class
No copy is made
Use as shareable resource
Can be used as global resource

main() is static to be called before any objects


exist
Member as static
Direct access of a member is possible, only if
that member is static
To get access you need to specify the name
of their class followed by the dot operator

ClassName.methodName()
ClassName.variableName
Static block
Can be used to initialize static
variables
Executes exactly once when that
class is loaded
System.out.println()
System is a final class of package java.lang
out is an instance of class PrintStream,
declare in class System as final static
println() is a method of PrintStream class
PrintStream is a class of package java.io
System class has only one constructor,
defined as private
Introducing final
final makes a field constant
So cannot be modified
You must initialize a final field during
declaration
Or value can be assigned within a
constructor

final double PI=3.14;


Array (ArrayTest.java)

length is instance variable


It holds size of an array
Dont be confused
length holds number of elements that
array is designed to hole
Introducing Nested and Inner classes
A class within another class
Inner class is accessed within same class
If a class Inner is defined within class Outer,
Inner doesnt exist independently of Outer
Outer class can access private members of
Inner class
Inner class also can access private member
of outer class
Inner class can be defined within a method
Exploring the String class
String is a class
Every string that has been created, also an
object of String class
System.out.println(CSE);
This CSE is also a String object
String are immutable
Contents cannot be altered
That problem has been solved by StringBuffer
Exploring the String class
Java defines + operator to concatenate
strings
String str = Oracle +Java +SE;
String has several methods
length() :: int
equals(String) :: boolean
charAt(int) :: char
Array of String
Using Command-Line Arguments
Uses to pass parameter during run-time
Passed parameter/s are received by main()
Parameter/s are stored in args[] as array
First command line argument is stored in
args[0]
Second command line argument is stored in
args[1]
And N-th command line argument is stored in
args[N]
Varargs : Variable-Length Arguments
A method that takes variable number of
arguments
It is done using array as parameter (Old Style)
Another option is use three periods (...)
Implicitly declare as an array of int
Any number of similar type argument can be
passed for both
Also array can be passed
Varargs : Variable-Length Arguments
A method can have normal parameter along
with a variable-length parameter
Varargs must be the last
Overloading Varargs Methods
Methods with different type of varargs
vaTest(int ... v)
vaTest(float ... v)
vaTest(boolean ... v)
vaTest(String ... v)
Varargs and Ambiguity
Methods with different type of varargs
vaTest(int ... v)
vaTest(float ... v)
vaTest(boolean ... v)
vaTest(String ... v)

If vaTest() is called
Chapter 8
Inheritance (Table.java & Table2.java)

One class can inherit properties of other


class
The class that has been inherited, is called
superclass
The class that inherits, is called subclass
extends is the key word that is used to
create a subclass
SubClassName extends SuperClassName{
}
Inheritance : single
class Furniture{
//class body class
} Furniture
class Table extends Furniture {
//class body
class Table
//copy of Furniture present here
}
Inheritance : multilevel
class Furniture{ class
//class body Furniture
}
class Table extends Furniture {
//class body
//copy of Furniture present here class Table
}
class Table2 extends Table {
//class body
//copy of Furniture & Table present here
} class
Table2
Inheritance : hierarchical
class Furniture{ class Furniture
//class body
}
class Table extends Furniture {
//class body
//copy of Furniture present here class class
} Table Desk
class Desk extends Furniture {
//class body
//copy of Furniture present here
}
Inheritance : multiple
interface interface
interface Furniture{ Table Desk
}
interface Furniture2{
}
class
class Table implements Furniture, Furniture2 {
Furniture
}
interface Furniture3 extends Furniture, Furniture2{
}
Inheritance : Java
A subclass can have only one superclass
Java does not support the inheritance of
multiple superclass into one sub class
Multiple inheritance using classes
Member Access and Inheritance
A subclass can access any public member of
superclass
A subclass cannot access any private
member of superclass
A Superclass Variable Can
Reference a Subclass Object (RefDemo.java)
A subclass can access any public member of
superclass
A subclass cannot access any private
member of superclass
Only members of the superclass are
accessable
Example :
SuperClass obj = new SubClass();
SuperClassObject=SubClassObject;
Using super
It refers immediate superclass
It has two forms
One calls superclass constructor
super(argument list);
Another is used to access member of superclass
super.member
Using super()
It must be the first statement of subclass
constructor
It can be used in any form according
superclass constructors
Superclass constructor is called that matches
the argument/s (during constructor
overloading)
Using super()
A superclass Surface has two constructors
Surface(){}
Surface(int l, int w){}
A subclass Box constructor has two
constructors
Box(){
Super(); // calls Surface()
}
Box(int l, int w, int h){
Super(l, w); //calls Surface(int l, int w)
}
Using super()
in a class hierarchy, if a superclass
constructor requires parameters,
then all subclasses must pass those
parameters
If there is no default constructor in
superclass and at least one
parameterized constructor present in
superclass
When constructors are called
If class hierarchy is created
From superclass to subclass
As super must be the first statement in subclass
constructor
This order is same if super() is used or
not
If not present, then default or parameter less
constructor is executed of superclass, if there is
default constructor in superclass
Method Overriding
In a class hierarchy, when a method in
a subclass has the same name and type
signature as a method in its superclass,
then the method in the subclass is said
to override the method in the
superclass
If a overridden method of subclass is
invoked, it always refers to subclass
method
Then superclass method will be then
hidden
Method Overloading
Method overriding occurs only
when the names and the type
signatures of the two methods are
identical
If they are not, then the two
methods are simply overloaded
super to call superclass
If overriding occurs, super is used
to call superclass method
super.superclassMethod()
Dynamic method dispatch
It is the mechanism by which a call
to an overridden method is resolved
at run time
Java implements run-time
polymorphism using this
Why overridden?
This allows the subclass the
flexibility to define its own methods
A general form of the methods that
will be used by all of its subclasses
Using Abstract Classes
A superclass that only defines a
generalized form that is shared by all
subclasses
If that class is inherited, subclass must
override that method
That superclass method is called
abstract method and superclass must be
abstract class
Instance of an abstract class cannot be
created
Using Abstract Class & method
abstract method doesnt have any body
If class contains abstract method, that
class must be declared as abstract
abstract keyword is used in front of
return type of a method
abstract keyword is used in front of class
keyword of a class
Using final
final key work is used to declare a
member variable as constant
final can be used with method
final void showArea() {
}
final can be used with class
final class Box {
}
Using final to prevent overriding
final can be used to prevent
overriding
final can be used with method
final void showArea() {
}
showAre() method cannot be
overridden
As the method is final
Using final to prevent overriding
If a subclass tries to override a final
method of a superclass, it is a compile-
time error
Late binding
Calls of methods are resolved during run-
time
Early binding
calls of methods are resolved during
compile time
It is done for final method
Using final to prevent inheritance
If a class is final, then that class
cannot be inherited
A class cannot have any subclass, if
that class has been declared as final
If a class is final, all methods of that
final class are final implicitly
The Object class
It is a special class
it is the superclass of all other
classes
Object class can refer to an object of
any other class
arrays are implemented as classes
So it works with Object class
Some methods of the Object class
equals(Object object) : boolean
getClass( ) : Class
hashCode( ) : int
notify( ) : void
notifyAll( ) : void
toString( ) : String
wait( ) : void
wait(long milliseconds) : void
wait(long milliseconds, int nanoseconds) : void
Reference/s

Java
The Complete Reference
by
Herbert Schildt

Вам также может понравиться