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

Object-Oriented Programming

Concepts in Java
Basic Object-Oriented concepts
(In Java everything is an object or a class )
Concept: An object has behaviors
In old style programming, you had:
data, which was completely passive
functions, which could manipulate any data
An object contains both data and methods that
manipulate that data
An object is active, not passive; it does things
An object is responsible for its own data
Example: A Rabbit object
You could (in a game, for example) create an
object representing a rabbit
It would have data:
How hungry it is
How frightened it is
Where it is
And methods:
eat, hide, run, dig
Concept: Classes describe objects
Every object belongs to (is an instance of) a class
An object may have fields, or variables
The class describes those fields
An object may have methods
The class describes those methods
A class is like a template, or cookie cutter
Concept: Classes are like
Abstract Data Types
An Abstract Data Type (ADT) bundles together:
some data, representing an object or "thing"
the operations on that data
Example: a CheckingAccount, with operations
deposit, withdraw, getBalance, etc.
Classes enforce this bundling together
Example of a class

class Employee {
// fields
String name;
double salary;

// a method
void pay () {
System.out.println("Pay to the order of " +
name + " $" + salary);
}
}
Approximate Terminology
instance = object
field = instance variable
method = function
sending a message to an object =
calling a function
These are all approximately true
Example of inheritance

class Person { class Employee


String name; extends Person {
String age; double salary;
void birthday () { void pay () { ...}
age = age + 1; }
}
}
Every Employee has a name, age, and birthday
method as well as a salary and a pay method.
Concept: Objects must be created
int n; does two things:
it declares that n is an integer variable
it allocates space to hold a value for n
Employee secretary; does one thing
it declares that secretary is type Employee
secretary = new Employee ( ); allocates the
space
Notation: How to declare and
create objects
Employee secretary; // declares secretary
secretary = new Employee (); // allocates space
Employee secretary = new Employee(); // both
But the secretary is still "blank"
secretary.name = "Adele"; // dot notation
secretary.birthday (); // sends a message
Concept: this object

Inside a class, no dots are necessary, because


you are working on this object
If you wish, you can make it explicit:
class Person { ... this.age = this.age + 1; ...}
this is like an extra parameter to the method
You usually don't need to use this
Concept: Constructors make objects
Every class has a constructor to make its objects
Use the keyword new to call a constructor
secretary = new Employee ( );
You can write your own constructors; but if you dont,
Java provides a default constructor with no arguments

The syntax for writing constructors is almost like that


for writing methods
Syntax for constructors
Instead of a return type and a name, just use the
class name
You can supply arguments

Employee (String theName, double theSalary) {


name = theName;
salary = theSalary;
}
Trick: Use the same name for a
parameter as for a field
A parameter overrides a field with the same name
But you can use this.name to refer to the field

Person (String name, int age) {


this.name = name;
this.age = age;
}
This is a very common convention
Concept: Classes themselves can
have fields and methods
Usually a class describes fields (variables) and
methods for its objects (instances)
These are called instance variables and instance methods
A class can have its own fields and methods
These are called class variables and class methods
There is exactly one copy of a class variable, not
one per object
Use the special keyword static to say that a field or
method belongs to the class instead of to objects
Example of a class variable

class Person {
String name;
int age;
static int population;
Person (String name) {
this.name = name;
this.age = 0;
population++;
}
}
Kinds of access

Java provides four levels of access:


public: available everywhere
protected: available within the package (in the same
subdirectory) and to all subclasses
[default]: available within the package
private: only available within the class itself
The default is called package visibility
In small programs this isn't important...right?
Java
Essentials of Java Programs
//Fig.2.1:Welcome1.java
//Textprintingprogram.

publicclassWelcome1{

//mainmethodbeginsexecutionofJavaapplication
publicstaticvoidmain(Stringargs[])
{
System.out.println("Hello"+args[0]+""+
args[1]);
System.out.println("WelcometoJavaProgramming!");

}//endmethodmain

}//endclassWelcome1
Essentials of Java Programs
Every program must have at least one class, and this
class name must be the same as the file name
Case sensitive

Every program must have a main method, but there


should only ever be one main method per program

Comments are the same as in C++

System.out.println outputs whatever is in the


parenthesis to the standard output (prompt)
Benefits of OO Programming
Better concepts and tools to model and represent the real
world as closely as possible (including concurrency, e.g., in
Windows GUI)
=> model of reality
=> behavior modeling

Better reusability & extensibility (inheritance)


=> reduce the time/cost of development
Enhanced maintainability & improved reliability
Encapsulation and Information Hiding
Object only accessible through the external interface
Internal implementation details are not visible outside

Help writing good program more easily


Difference between data abstraction
and Encapsulation
Data Abstraction is removing unneccessary datas.
Data Encapsualation is wrapping up the data into
the single frame called class,for further
reuseablity.
Encapsulation means we hide the data from
directly interaction
Abstraction means we bother about what the
object can do but don't bother about how it does?
Operator Overloading
Customised behaviour of operators
you can give special meanings to operators,
when they are used with user-defined classes.
This is called operator overloading
You can implement C++ operator overloads by
providing special member-functions on your classes
that follow a particular naming convention.
For example, to overload the + operator for your
class, you would provide a member-function named
operator+ on your class.
Note:-Java does not support operator
overloading.
Example operator overloading
200 + 300=500
Din + esh=Dinesh
The process of making an operator to exhibit
different behavior at different instance is called
operator overloading.
Dynamic Binding
Dynamic Binding or Late Binding

Dynamic Binding refers to the case where compiler is not able to


resolve the call and the binding is done at runtime only.
Static Binding or Early Binding

If the compiler can resolve the binding at the compile time only then
such a binding is called Static Binding or Early Binding.
All the instance method calls are always resolved at runtime,
but all the static method calls are resolved at compile time itself and
hence we have static binding for static method calls.
Because static methods are class methods and hence they can be
accessed using the class name itself .
How to enter the value in java
import java.io.*;
class d{
public static void main(String arg[]) throws Exception
{
String f;
int i;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter the value");


f=b.readLine();
System.out.println("enter the interger value");
i=Integer.parseInt(b.readLine());
System.out.println("value is"+f);
System.out.println("integer vlaue is :"+i);

}
}
Run Applet
import java.awt.*;
import java.applet.*;
public class myap extends Applet
{
String str=" ";
public void init()
{
str="init";
}
public void paint(Graphics g)
{
g.drawString(str,50,80);
}
/*<applet code="myap" height=200 width=300> </applet>*/
}
C:\Program Files\Java\jdk1.6.0\bin>javac d.java

C:\Program Files\Java\jdk1.6.0\bin>java d
enter the value
dd
enter the interger value
34
value isdd
integer vlaue is :34

C:\Program Files\Java\jdk1.6.0\bin>javac myap.java

C:\Program Files\Java\jdk1.6.0\bin>appletviewer myap.java

C:\Program Files\Java\jdk1.6.0\bin>javac myap.java


Command line main(String arg)
//command line

class testcommand{
public static void main(String arg[])
{
int count,i=0;
String st;
count=arg.length;
System.out.println("no of argument"+count);
while(i<count)
{
st=arg[i];
i=i+1;
System.out.println(st);
}
}
}
Command line argument
C:\Program Files\Java\jdk1.6.0\bin>java
testcommand 1 3 5 7 87
no of argument5
1
3
5
7
87
Abstract Data Types

Any Data type which is not supported natively by a


programming language is called an Abstract Data Type.
An Abstract Data Type (ADT) is more a way of looking at
a data structure: focusing on what it does and ignoring how
it does its job. A stack or a queue is an example of an ADT.
It is important to understand that both stacks and queues
can be implemented using an array. It is also possible to
implement stacks and queues using a linked list. This
demonstrates the "abstract" nature of stacks and queues:
how they can be considered separately from their
implementation.
Since Java has an abundance of ready made classes (the
API).
Break the term "data type" and
"abstract".
Data type
When we consider a primitive type we are actually
referring to two things: a data item with certain
characteristics and the permissible operations on
that data. An int in Java, for example, can contain
any whole-number value from -2,147,483,648 to
+2,147,483,647. It can also be used with the
operators +, -, *, and /. understanding the type
means understanding what operations can be
performed on it.
ADT
We can further extend the meaning of the ADT when
applying it to data structures such as a stack and queue. In
Java, as with any class, it means the data and the
operations that can be performed on it. In this context,
although, even the fundamentals of how the data is stored
should be invisible to the user. Users not only should not
know how the methods work, they should also not know
what structures are being used to store the data.
Consider for example the stack class. The end user knows
that push() and pop() (amoung other similar methods) exist
and how they work. The user doesn't and shouldn't have to
know how push() and pop() work, or whether data is stored
in an array, a linked list, or some other data structure like a
tree.
Collection Framework
The Collections Framework provides a well-designed set
of interfaces and classes for storing and manipulating
groups of data as a single unit, a collection. The framework
provides a convenient API to many of the abstract data
types familiar from computer science data structure
curriculum: maps, sets, lists, trees, arrays, hashtables, and
other collections. Because of their object-oriented design,
the Java classes in the Collections Framework encapsulate
both the data structures and the algorithms associated with
these abstractions. The framework provides a standard
programming interface to many of the most common
abstractions, without burdening the programmer with too
many procedures and interfaces.
Collections Framework

Reduces the effort required to learn APIs


Reduces the effort required to design and
implement APIs
Set and List are subinterfaces of Collection.

36
Java.util.Collection interface
A Java collection is any class that holds objects and
implements the Collection interface

For example, the ArrayList<T> class is a Java collection class,


and implements all the methods in the Collection interface

The Collection interface is the highest level of Java's


framework for collection classes

All of the collection classes discussed here can be found in


package java.util
Dynamic Binding
(late binding, virtual binding)
A mechanism by which, when the compiler can't
determine which method implementation to use in
advance, the runtime system (JVM) selects the
appropriate method at runtime, based on the class
of the object .
The process of binding a call to a particular
method. This is performed dynamically at run-
time due to the presence of polymorphism

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