Vous êtes sur la page 1sur 17

Unti-1

Syllabus:-

Object oriented thinking :- Need for oop paradigm, A way of viewing world – Agents,
responsibility, messages, methods, classes and instances, class hierarchies (Inheritance),
method binding, overriding and exceptions, summary of oop concepts, coping with
complexity, abstraction mechanisms.

The OOP Paradigm

Object oriented programming (OOP), as the name suggests, is a paradigm where we


focus real life objects while programming any solution. By focusing real life objects we
mean that over solutions revolves around different objects, which represent respective
objects in real life situation. We not only write programs to process data, we actually
write behaviours of our programming objects, those behaviours are called methods in
objected oriented programming. The data elements on which those objects behave, are
called data-members/ fields.

Object-Oriented (Real World Case): Agents Messaging

A way of viewing the world:


A way of viewing the world Suppose I wish to send flowers to a friend (Sally) who lives
in a city many miles away. Solution 1: Pick up flowers and carry them to Sally’s door.
(might be romantic, but not practical) Solution 2: I can go to Flora (my local florist), tell
her the variety and quantity of flowers I wish to send, and give her Sally’s address.

Agents and Communities:


Agents and Communities The mechanism I used to solve my problem was to find an
agent (Flora), and to pass to her a message containing my request. It is the responsibility
of Flora to satisfy my request. There involves some methods (some algorithms or a set of
operations) used by Flora to do this.

Agents and Communities - 2:


Agents and Communities - 2 I do not need to know the particular method Flora will use
to satisfy my request. This information is hidden from my inspection. If I investigated,
however, I might discover that Flora delivers a slightly different messages to another
florist in Sally’s city. That florist, in turn, perhaps has a subordinate who makes this
“floral arrangement”.

Agents and Communities - 3:


Agents and Communities - 3 The florist (in Sally’s city) then passes the flowers along
with another message to a delivery person and so on. Earlier, the florist in Sally’s city had
obtained her flowers from a flower wholesaler who, in turn, had interactions with the
flower growers, each of whom had to manage a team of gardeners.

Agents and Communities - 4:


The solution to my problem required the help of many other individuals. Without their
help, my problem could not be easily solved. Me Flora Sally Delivery person Flower
arranger Gardeners Growers Wholesaler Sally’s florist Agents and Communities - 4

Agents and Communities - 5:


Agents and Communities - 5 An object-oriented program is structured as a community of
interacting agents, called objects. Each object has a role to play. Each object provides a
service, or performs an action, that is used by other members of the community.

Messages and Methods:


Messages and Methods My request to Flora initiated a chain reaction of requests until my
flowers ultimately reached my friend. We see that members of this community interact
with one another by making requests. Action is initiated (in object-oriented
programming) by the transmission of a message to an agent (an object) responsible for
the action.

Messages and Methods - 2:


Messages and Methods - 2 The message encodes the request for an action and is
accompanied by an additional information (arguments) needed to carry out the request.
The receiver is the object to whom the message is sent.

Messages and Methods - 3:


Messages and Methods - 3 If the receiver accepts the message, it accepts the
responsibility to carry out the indicated action. In response to a message, the receiver will
perform some methods to satisfy the request. The principle of information hiding: The
client sending the request need not know the actual means by which the request will be
honored.

Messages and Methods - 4:


Messages and Methods - 4 A message has a designated receiver; the receiver is a
particular object to which the message is sent. The interpretation of the message (the
method used to respond to the message) is dependent on the receiver and can vary with
different receivers. If I ask Kenneth, my dentist, to send flowers to my friend, he may not
have a method for solving that problem. If he understands the request at all, he will
probably issue an appropriate error diagnostic.

Classes and Instances:


Classes and Instances I have a rough idea of the behavior I can expect when I walk into
Flora’s shop and present my request. I am able to make certain assumptions because I
have general information about florists in general, and I expect that Flora (being an
instance of this category) will fit the general pattern. We can use the term Florist to
represent the category (or class) of all florists.

Classes and Instances - 2:


Classes and Instances - 2 All objects are instances of a class. The method invoked by an
object in response to a message is determined by the class of the receiver. All objects of a
given class use the same method in response to similar messages.

Class Hierarchies (Inheritance):


Class Hierarchies (Inheritance) I have more information about Flora because she is a
shopkeeper. I know for example that I probably will be asked for money as part of the
transaction, and in return for payment I will be given a receipt. These actions are true for
other shopkeepers. Since the category Florist is a more specialized form of the category
shopkeeper, any knowledge I have on Shopkeepers is also true of florists (and hence of
Flora).

Class Hierarchies (Inheritance) - 2:


Class Hierarchies (Inheritance) - 2 One way to think about how I have organized my
knowledge of Flora is in terms of a hierarchy of categories: Flora is a Florist. Florist is a
specialized form of Shopkeeper. Shopkeeper is a human, etc.

Class Hierarchies (Inheritance) - 3:


Florist Flora Shopkeeper Human Class Hierarchies (Inheritance) - 3 The principle that
knowledge of a more general category is also applicable to a more specific category is
called inheritance. We say that the class Florist will inherit attributes of the class (or
category) Shopkeeper.

Class Hierarchies (Inheritance) - 4:


Class Hierarchies (Inheritance) - 4 Information about all members of Material Object is
equally applicable to Flora and to her Flowers. The idea of inheritance: Classes can be
organized into a hierarchical inheritance structure. A child class (or subclass) will inherit
attributes from a parent class (or superclass) higher in the tree. An abstract parent class
(or interface) is the one (such as Mammal) for which there are no direct instances; it is
used only to create subclasses.
In a more in-depth view towards OOP using domain specific terminology, following are
the fundamental features we get:

Encapsulation
Inheritance
Re-usability
Information Hiding

Encapsulation:
The way we make a logical boundary around behaviours (methods) and data (properties)
they work on is called Encapsulation.

Inheritance:
As in real life, objects in OOP relate to each other in one way or another, the relationship
in most of the case is parent/child relationship. The child objects inherent all the
functionalities (methods) and data (properties) of their parents.

Re-usability
Along with inheritance, some other phenomena like method overloading and overriding,
provide code-reuse, which is known to be a very basic feature of object oriented
programming.

Information Hiding
When we have ways to reuse our code through one way or other, we are also in need of
some security regarding our source code. To protect it from unauthorized access/
alteration. In object oriented programming, this is called Information Hiding and is
achieved through "Access Modifiers" which lets us restrict access to all or some parts of
our objects methods and/or data

What is a Class

• Class is blue print or an idea of an Object


• From One class any number of Instances can be created
• It is an encapsulation of attributes and methods

class
FIGURE
Ob1 Ob3

CIRCLE Ob2 SQUARE


RECTANGLE
Class Declaration Syntax

class <ClassName>
{
attributes/variables;
Constructors();
methods();
}

Instance

• Instance is an Object of a class which is an entity with its own attribute values and
methods.

Creating an Instance

ClassName refVariable;
refVariable = new Constructor();
or
ClassName refVariable = new Constructor();

Inheritance

• Inheritance allows to reuse classes by deriving a new class from an existing one
• The existing class is called the parent class, or superclass, or base class
• The derived class is called the child class or subclass.
• The child class inherits characteristics of the parent class(i.e the child class
inherits the methods and data defined for the parent class

Method Binding

• Objects are used to call methods.


• MethodBinding is a mechanism by which a call to a method is determined. It is
legal for a class to have two or more methods with the same name.
• Java has to be able to uniquely associate the invocation of a method with its
definition relying on the number and types of arguments.
• Therefore the same-named methods must be distinguished:
1) by the number of arguments, or
2) by the types of arguments
• Overloading and inheritance are two ways to implement polymorphism.
Method Overriding

 There may be some occasions when we want an object to respond to the same
method but have different behaviour when that method is called.
 That means, we should override the method defined in the superclass. This is
possible by defining a method in a sub class that has the same name, same
arguments and same return type as a method in the superclass.
 Then when that method is called, the method defined in the sub class is invoked
and executed instead of the one in the superclass. This is known as overriding.

Exception

• Exception is an abnormal condition that arises in the code sequence.


• Exceptions occur during compile time or run time.
• “throwable” is the super class in exception hierarchy.
• Compile time errors occurs due to incorrect syntax.
• Run-time errors happen when
– User enters incorrect input
– Resource is not available (ex. file)
– Logic error (bug) that was not fixed

Summary of oops

The following are the basic oops concepts: They are as follows:
1. Objects.
2. Classes.
3. Data Abstraction.
4. Data Encapsulation.
5. Inheritance.
6. Polymorphism.
7. Dynamic Binding.
8. Message Passing
Unit-II
Syllabus

History of Java, Java buzzwords, datatypes, variables, scope and life time of variables,
arrays, operators, expressions, control statements, type conversion and costing, simple
java program, classes and objects – concepts of classes, objects, constructors, methods,
access control, this keyword, garbage collection, overloading methods and constructors,
parameter passing, recursion, string handling.

Evolution

• Computer language innovation and development occurs for two fundamental


reasons:
1) to adapt to changing environments and uses
2) to implement improvements in the art of programming
• The development of Java was driven by both in equal measures.
• Many Java features are inherited from the earlier languages:

Before Java C

• Designed by Dennis Ritchie in 1970s.


• Before C: BASIC, COBOL, FORTRAN, PASCAL
• C- structured, efficient, high-level language that could replace assembly code
when creating systems programs.
• Designed, implemented and tested by programmers.

Before Java C++

• Designed by Bjarne Stroustrup in 1979.


• Response to the increased complexity of programs and respective improvements
in the programming paradigms and methods:
1) assembler languages
2) high-level languages
3) structured programming
4) object-oriented programming (OOP)
• OOP – methodology that helps organize complex programs through the use of
inheritance, encapsulation and polymorphism.
• C++ extends C by adding object-oriented features.

Java, having been developed in 1991, is a relatively new programming language. At that
time, James Gosling from Sun Microsystems and his team began designing the first
version of Java aimed at programming home appliances which are controlled by a wide
variety of computer processors.

Gosling's new language needed to be accessible by a variety of computer processors.


In 1994, he realized that such a language would be ideal for use with web browsers and
Java's connection to the internet began. In 1995, Netscape Incorporated released its latest
version of the Netscape browser which was capable of running Java programs.

Why is it called Java? It is customary for the creator of a programming language to


name the language anything he/she chooses. The original name of this language was
Oak, until it was discovered that a programming language already existed that was named
Oak. As the story goes, after many hours of trying to come up with a new name, the
development team went out for coffee and the name Java was born.

While Java is viewed as a programming language to design applications for the


Internet, it is in reality a general all purpose language which can be used independent of
the Internet.

Java has become so successful and essentially cemented its position as an industry
standard for many reasons:

• C++ is powerful, but also dangerous. The power and popularity of C derived from
the extensive use of pointers. However, any incorrect use of pointers can cause
memory leaks, leading the program to crash.
• In a complex program, such memory leaks are often hard to detect.
• Robustness is essential. Users have come to expect that Windows may crash or
that a program running under Windows may crash. (“This program has performed
an illegal operation and will be shut down”)
• However, users do not expect toasters to crash, or washing machines to crash.
• A design for consumer electronics has to be robust.
• Replacing pointers by references, and automating memory management was the
proposed solution.

It works with almost any operating system. Since it is run through what is called a
"virtual machine" regardless of what kind of computer you are using, chances are Java
will run smoothly.

It is object-oriented. In computer programming terms, an object is not markedly


different than an object in the real world. Computer programming instructors often
explain object-oriented programming using the "lamp" analogy. An object is simply an
entity, such as a lamp, that has both a state (on and off) and a behavior (turn on and turn
off). To say that Java is object-oriented means that the programming is based on these
objects and how they interact. This is advantageous because it makes for simpler code
writing.
It is simple to use. Much of the syntax, or the rules that determine what combination of
symbols means what, is based on C++. Java improved upon this model, making it more
object- oriented and easier to write and understand.

It is secure. The same Virtual Machine that makes Java almost universally compatible
also keeps it secure. Since it is run in a self-contained program within your computer, any
glitches or errors that occur don't wreak havoc outside of the system.

With these features, Java has maintained its niche in the computer programming market.
It is estimated that as of 2006 there were over four billion devices worldwide that are
capable of running Java Virtual Machine. Java is still widely used to this day, and, as of
May 2007, almost all of Java's core code is available to download for free.

Java Buzz Words

• The key considerations were summed up by the Java team in the following list of
buzzwords:
 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Multithreaded
 Architecture-neutral
 Interpreted
 High performance
 Distributed
 Dynamic

Its Simple

Java was designed to be easy for the professional programmer to learn and use
effectively. If you already understand the basic concepts of OOPS, learning Java
will be even easier.

Its Secure

The key that allows Java to solve security problems just described is that the
output of a Java compiler is not executable code. Rather, it is bytecode

Its Portable
The key that allows Java to solve and the portability problems just described is
that the output of a Java compiler is not executable code. Rather, it is bytecode.
Translating a Java program into bytecode helps makes it much easier to run a
program in a wide variety of environments. This reason is straightforward: only
the JVM needs to be implemented for each platform.

Object-Oriented

Java is Object Oriented programming language. The object model in Java is


simple and easy to extend.

Robust

The ability to create robust programs was given high priority in the design of
Java. In a well written Java program, all run-time errors can and should be
managed by your program.

Multithreaded

Java was designed to meet the real-world requirement of creating interactive,


networked programs. Java supports multithreaded programming, which allows
you to write programs that do many things simultaneously.

Architecture-neutral

Write once; run anywhere, any time, forever.

Interpreted

Java enables the creation of cross-platform programs by compiling into an


intermediate representation called Java bytecode. This code can be interpreted
on any system that provides a Java Virtual Machine.

Distributed

Java is designed for the distributed environment of the Internet, because it


handles TCP/IP protocols.

Dynamic

Java programs carry with them substantial amounts of run time type information
that is used to verify and resolve accesses to objects at run time.
Data Types

The data types in the Java programming language are divided into two categories and
can be explained using the following hierarchy structure :

• Primitive Data Types


• Reference Data Types

Primitive Data Types

The primitive data types are predefined data types, which always hold the value of
the same data type, and the values of a primitive data type don't share the state with
other primitive values. These data types are named by a reserved keyword in Java
programming language.
There are eight primitive data types supported by Java programming language :
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128
to127 (inclusive). This type of data type is useful to save memory in large arrays..
We can also use byte instead of int to increase the limit of the code. The syntax of
declaring a byte type variable is shown as:
byte b = 5;
short
The short data type is a 16-bit signed two's complement integer. It ranges from
-32,768 to 32,767. short is used to save memory in large arrays. The syntax of
declaring a short type variable is shown as:
short s =
2;
int
The int data type is used to store the integer values not the fraction values. It is a 32-
bit signed two's complement integer data type. It ranges from -2,147,483,648 to
2,147,483,647 that is more enough to store large number in your program. However
for wider range of values use long. The syntax of declaring a int type variable is shown
as:
int num =
50;
long
The long data type is a 64-bit signed two's complement integer. It ranges from
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with
larger range of values. The syntax of declaring a long type variable is shown as:
long ln =
746;
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from
1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use
a float (instead of double) to save memory in large arrays. We do not use this data type
for the exact values such as currency. For that we have to use java.math.BigDecimal
class. The syntax of declaring a float type variable is:
float f = 105.65;

float f =
-5000.12;
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).
This data type is generally the default choice for decimal values. The syntax of
declaring a double type variable is shown as:
double d =
6677.60;
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to
65,535. They are not integral data type like int, short etc. i.e. the char data type can't
hold the numeric values. The syntax of declaring a char type variable is shown as:
char caps = 'c';
boolean
The boolean data type represents only two values: true and false and occupy is 1-
bit in the memory. These values are keywords in Java and represents the two boolean
states: on or off, yes or no. We use boolean data type for specifying conditional
statements as if, while, do, for. In Java, true and false are not the same as True and
False. They are defined constants of the language. The syntax of declaring a boolean
type variable is shown as:
boolean result =
true;
The ranges of these data types can be described with default values using the
following table:
Default
Data Value Size (in
Minimum Range Maximum Range
Type (for bits)
fields)
Occupy
byte 0 8 bits in -128 +127
memory
Occupy
short 0 16 bits in -32768 +32767
memory
Occupy
int 0 32 bits in -2147483648 +2147483647
memory
Occupy
long 0L 64 bits in -9223372036854775808 +9223372036854775807
memory
Occupy
32-bit
IEEE 1.40129846432481707e-
float 0.0f 3.40282346638528860e+38
754 45
floating
point
Occupy
64-bit
IEEE 4.94065645841246544e-
double 0.0d 1.79769313486231570e+308d
754 324d
floating
point
Occupy
16-bit,
char '\u0000' unsigned 0 to 65,535
Unicode
character
Occupy
boolean false 1- bit in NA NA
memory
When we declare a field it is not always essential that we initialize it too. The compiler
sets a default value to the fields which are not initialized which might be zero or null.
However this is not recommended.
Integer Data Types
So far you would have been known about these data types. Now lets take an Integer
data type in brief to better understand:
As we have told that an integer number can hold a whole number. Java provides four
different primitive integer data types that can be defined as byte, short, int, and long
that can store both positive and negative values. The ranges of these data types can be
described using the following table:
Data Size (in
Minimum Range Maximum Range
Type bits)
Occupy 8
byte bits in -128 +127
memory
Occupy
short 16 bits in -32768 +32767
memory
Occupy
int 32 bits in -2147483648 +2147483647
memory
Occupy -
long 64 bits in 922337203685477580 +9223372036854775807
memory 8
Examples of floating-point literals are:
0
1
123
-42000

Floating-point numbers
A floating-point number represents a real number that may have a fractional values i.e.
In the floating type of variable, you can assign the numbers in an in a decimal or
scientific notation. Floating-point number have only a limited number of digits, where
most values can be represented only approximately. The floating-point types are float
and double with a single-precision 32-bit IEEE 754 floating point and double-
precision 64-bit IEEE 754 floating point respectively. Examples of floating-point
literals are:
10.0003
48.9
-2000.15
7.04e12

Declaring Variables
To use any variable in a Java program, you must first declare it. Variable declarations
consist of a type and a variable name:

int myAge;

String myName;

boolean isTired;

Variable definitions can go anywhere in a method definition (that is, anywhere a regular
Java statement can go), although they are most commonly declared at the beginning of
the definition before they are used:

public static void main (String args[ ] ) {

int count;

String title;the

boolean isAsleep;

...

You can string together variable names with the same type:

int x, y, z;

String firstName, LastName;

You can also give each variable an initial value when you declare it:

int myAge, mySize, numShoes = 28;

String myName = "Laura";

boolean isTired = true;

int a = 4, b = 5, c = 6;

If there are multiple variables on the same line with only one initializer (as in the first of
the previous examples), the initial value applies to only the last variable in a declaration.
You can also group individual variables and initializers on the same line using commas,
as with the last example, above. Local variables must be given values before they can
be used (your Java program will not compile if you try to use an unassigned local
variable). For this reason, it's a good idea always to give local variables initial values.
Instance and class variable definitions do not have this restriction (their initial value
depends on the type of the variable: null for instances of classes, 0 for numeric
variables, '\0' for characters, and false for booleans).

Points on Variable Names

• Variable names in Java can start with a letter, an underscore (_), or a dollar sign
($).
• They cannot start with a number.
• After the first character, your variable names can include any letter or number.
• Symbols, such as %, *, @, and so on, are often reserved for operators in Java,
so be careful when using symbols in variable names.
• In addition, the Java language uses the Unicode character set. Unicode is a
character set definition that not only offers characters in the standard ASCII
character set, but also several million other characters for representing most
international alphabets.

Java language is case-sensitive, which means that uppercase letters are different from
lowercase letters. This means that the variable X is different from the variable x, and a
pen is not a Pen is not a PEN. Keep this in mind as you write your own Java programs
and as you read Java code other people have written.

Scope and life time of a variable

Scope determines the visibility of program elements with respect to other program
elements.

In Java, scope is defined separately for classes and methods:


1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
A scope is defined by a block:
{

}
A variable declared inside the scope is not visible outside:
{
int n;
}
n = 1;// this is illegal

The variable is destroyed once the scope in which it is defined is closed or ended. The
scope starts once the main block of the program start or it can be started explicitly by
starting a block using open brackets({). The scope ends once we end the block by closing
the brackets(}).

Sample program

Class Scope
{
Public static void main(String args[])
{

Int x=10;
System.out.println( “x = “+x+” y = +y);
{
Int y=20;
System.out.println( “x = “+x+” y = +y);

}
// System.out.println( “x = “+x+” y = +y);
//y cannot be accessed because y is not known;
}

Vous aimerez peut-être aussi