Vous êtes sur la page 1sur 48

Programme

Object Oriented Programming Brief Introduction

Classes and instances

Object Oriented Programming Brief Introduction


Classes and instances

Programme

Object Oriented Programming Brief Introduction

Classes and instances

Object Oriented Programming Brief Introduction


Classes and instances

Object oriented programming

Classes are models of real world entities inside our programs.


Classes may have data members and methods. For example, a
Person class can have a data member name of type String,
and a method eat() of type void.
OO Design deals with designing the classes to solve a problem.
OO Programming deals with realizing that design correctly.

Object Oriented Programming Brief Introduction


Classes and instances

Programme

Object Oriented Programming Brief Introduction

Classes and instances

Object Oriented Programming Brief Introduction


Classes and instances

A class structure

Class definition specifies data members each instance (object) of the class will have
methods, including instance methods that are called on
instances/ objects and class methods or static methods that
are called on the class directly without invoking objects.

Object Oriented Programming Brief Introduction


Classes and instances

Example: Javas String class

As we know String is a built in class for handling sequences of


characters.
We can think of it as a Java type, just like int, double,
boolean. (But String is a non-primitive type.)
Inside, it stores a sequence of characters (how, we dont care
right now).
The interface provides a number of operations on the
character sequence.

Object Oriented Programming Brief Introduction


Classes and instances

Example: String object

1
2

S t r i n g g r e e t i n g = H e l l o , World ! ;
System . o u t . p r i n t l n ( g r e e t i n g . l e n g t h ( ) ) ;

Here, greeting is an instance, or, object of String class. The


statement String greeting = "Hello, World!"; is called the
instantiation statement. The class has an instance method
length that is being invoked on object greeting

Object Oriented Programming Brief Introduction


Classes and instances

Standard way of instantiatiation

1
2

S t r i n g l e c t u r e r 1 = Gaurav ;
S t r i n g l e c t u r e r 2 = new S t r i n g ( S c o t t ) ;
The two variables are different instances of the String class.
First is known as lazy instantiation, just for Strings.
Second (using new) is generally how we create instances.
More information about this will come a bit later in this
lecture ...

Object Oriented Programming Brief Introduction


Classes and instances

Defining classes
Defining a class
Each class is defined in a separate file with the same name
and ending with . java
All Java class definitions are separate files in the same folder
(for now).
Adding instance variables
Instance variables can be declared as in the following two
examples. Note the public modifier (for now):
1
2

public int
public String

instanceVar1 ;
instanceVar2 ;

Object Oriented Programming Brief Introduction


Classes and instances

Defining methods

Method definitions have a heading and a method body


The heading defines the name of the method and other useful
information.
The body defines the code to be executed when the method is
called.

Object Oriented Programming Brief Introduction


Classes and instances

Defining a class: example


1
2
3

public class Rectangle {


p u b l i c double w i d t h ;
p u b l i c double h e i g h t ;

p u b l i c double a r e a ( ) {
return width height ;
}

5
6
7
8

p u b l i c double p e r i m e t e r ( ) {
return 2( width + h e i g h t ) ;
}

9
10
11
12

Object Oriented Programming Brief Introduction


Classes and instances

Defining a class: example

Note that the above class definition merely provides a template or


blueprint for the class. No complete program using this class has
yet been written, and no object (instance) of this class has yet
been created.

Object Oriented Programming Brief Introduction


Classes and instances

Exercise - define a class

v EXERCISE TIME! w
Define a class for a Circle that is represented by its radius.

Object Oriented Programming Brief Introduction


Classes and instances

Declaration and instantiation


An object or instance of the new class type is declared in main
as follows:
1
2

ClassName c l a s s V a r ; // d e c l a r a t i o n
R e c t a n g l e r e c t ; // e x a m p l e

Object Oriented Programming Brief Introduction


Classes and instances

Declaration

Declaration creates a reference in the memory, which doesnt refer


to any storage space yet.

Object Oriented Programming Brief Introduction


Classes and instances

Declaration and instantiation


To allocate storage space for the instance variables of the
object declared and to refer to that memory, we perform the
instantiation statement.
1
2

c l a s s V a r = new ClassName ( ) ; // i n s t a n t i a t i o n
r e c t = new R e c t a n g l e ( ) ; // e x a m p l e

Object Oriented Programming Brief Introduction


Classes and instances

Declaration and instantiation

These can be combined:


1
2

ClassName c l a s s V a r = new ClassName ( ) ;


// d e c l a r a t i o n + i n s t a n t i a t i o n

3
4

R e c t a n g l e r e c t = new R e c t a n g l e ( ) ; // e x a m p l e

Object Oriented Programming Brief Introduction


Classes and instances

Exercise - Declaring and Instantiating an object

v EXERCISE TIME! w
Declare and instantiate an object myCircle of class Circle
that has a radius of 2.4

Object Oriented Programming Brief Introduction


Classes and instances

The dot (.) operator

The dot operator gives us access to the members (instance


variables and method) for an object. Think of it as the
apostrophe s (s) of the human language (as in Gauravs class
or Matts workshop)

Object Oriented Programming Brief Introduction


Classes and instances

The dot (.) operator

R e c t a n g l e m y R e c t a n g l e = new R e c t a n g l e ( ) ;
// e x a m p l e
myRectangle . width = 5 ;

Object Oriented Programming Brief Introduction


Classes and instances

The dot (.) operator

The expression myRectangle gives us access to the instance


variable width of object myRectangle.
When a method is invoked on an object using the dot
operator, it calls the method as defined in the class in the
context of that object and any data members used in that
method are the ones belonging to that object.

Object Oriented Programming Brief Introduction


Classes and instances

The dot (.) operator

1
2
3
4

R e c t a n g l e m y R e c t a n g l e = new R e c t a n g l e ( ) ;
myRectangle . width = 5 ;
myRectangle . h e i g h t = 8 ;
System . o u t . p r i n t l n ( m y R e c t a n g l e . a r e a ( ) ) ;

Here, myRectangle.area() returns width * height and since


the method is called on object myRectangle, it returns
myRectangle * myRectangle. Had the method been called on
another object yourRectangle, it would return yourRectangle
* yourRectangle.

Object Oriented Programming Brief Introduction


Classes and instances

Exercise - Accessing instance variables and calling methods

v EXERCISE TIME! w
Write a piece of code that sits outside the class definition and
displays the radius of the object myCircle and also its area.

Object Oriented Programming Brief Introduction


Classes and instances

Are there any default values? I

Each instance variables is automatically initialized to the


default value for its type when an object of the class is
created.
For example, an instance variable of type int is given the
default value 0;
And an instance variable of type String (or any class type) is
given the default value null. (More about null later.)

Object Oriented Programming Brief Introduction


Classes and instances

Bad client, bad bad client!

Once the object is created, we can start operating on it.


1
2
3
4
5

Rectangle rect = new Rectangle () ;


rect . width = -5; // : o : O
rect . height = 8;
System . out . println ( rect . area () ) ;
// displays -40 : (

Object Oriented Programming Brief Introduction


Classes and instances

Changing visibility to private


1
2
3

public class Rectangle {


p r i v a t e double w i d t h ;
p r i v a t e double h e i g h t ;

p u b l i c double a r e a ( ) {
return width height ;
}

5
6
7
8

p u b l i c boolean i s S q u a r e ( ) {
r e t u r n ( w i d t h == h e i g h t ) ;
}

9
10
11
12

Object Oriented Programming Brief Introduction


Classes and instances

Changing visibility to private

Now, the instance variables width and height are visible only
within the class definition.

Object Oriented Programming Brief Introduction


Classes and instances

How does one access (read/write) private data members

We access (read and write) private instance variables through


public methods called getters and setters.
getters return the value of the data member to the caller.
setters set the value supplied by the caller to the data
members.

Object Oriented Programming Brief Introduction


Classes and instances

How does one access (read/write) private data members

1
2
3

4
5
6
7
8
9

public class Rectangle {


p r i v a t e double width , h e i g h t ;
p u b l i c double g e t W i d t h ( ) { r e t u r n w i d t h
; }
p u b l i c v o i d s e t W i d t h ( double w) {
w i d t h = Math . a b s (w) ;
}
// . . . same f o r h e i g h t
// r e s t o f t h e c l a s s d e f i n i t i o n . . .
}

Object Oriented Programming Brief Introduction


Classes and instances

Setters provide validation

You can see that we validated the passed values before assigning
to the instance variable as width = Math.abs(w). This is a
typical case and setters are in charge of validating data before
assigning it to the instance variables.

Object Oriented Programming Brief Introduction


Classes and instances

Setters provide validation

Object Oriented Programming Brief Introduction


Classes and instances

Exercise - Adding getters and setters

v EXERCISE TIME! w
Add getters and setters to class Circle. The setter should
result in radius becoming zero if the parameter passed is not
positive.

Object Oriented Programming Brief Introduction


Classes and instances

Exercise - Write a client

v EXERCISE TIME! w
Write a client (code sitting outside Circle.java, for
example, in the main method of another class) that performs
the following operations,
Declare and instantiate object myCircle of class Circle
that has a radius of 1.8
Display radius of myCircle.
Increase radius of myCircle by 1.4

Object Oriented Programming Brief Introduction


Classes and instances

I wish creating objects was easier


Lets say that the user wants to create a Rectangle whose width
is 5 and height is 8. Following code achieves this,
1
2
3

R e c t a n g l e r e c t = new R e c t a n g l e ( ) ;
r e c t . width = 5;
rect . height = 8;

However, it would be really nice if one could pass the values for the
data members in the instantiation statement itself, as,
1

R e c t a n g l e r e c t = new R e c t a n g l e ( 5 , 8 ) ;

This is done through constructors.

Object Oriented Programming Brief Introduction


Classes and instances

Constructors

A constructor is a method defined in the class.


A constructor must have the same name as the class.
A constructor has no return type (not even void).
There may be multiple constructors, each distinguished by its
parameter list. Thus, we may have one constructor with no
parameters, and another with one int parameter.
A suitable constructor is automatically called during
instantiation based on number of parameters passed. If an
appropriate constructor is not found, a compilation error is
generated.

Object Oriented Programming Brief Introduction


Classes and instances

Constructor - example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

public class Rectangle {


p r i v a t e double width , h e i g h t ;
// g e t t e r s and s e t t e r s
p u b l i c R e c t a n g l e ( ) { // d e f a u l t c o n s t r u c t o r
setWidth (1) ;
setHeight (1) ;
}
// p a r a m e t e r i z e d c o n s t r u c t o r f o r a s q u a r e
p u b l i c Rectangle ( double s i d e ) {
setWidth ( s i d e ) ;
setHeight ( side ) ;
}
// p a r a m e t e r i z e d c o n s t r u c t o r g e n e r i c
p u b l i c Rectangle ( double w, double h ) {
s e t W i d t h (w) ;
setHeight (h) ;
}
// r e s t o f t h e c o d e
}

Object Oriented Programming Brief Introduction


Classes and instances

Constructor - example

Object Oriented Programming Brief Introduction


Classes and instances

Constructors should call setters - always!

Constructors should always use setters to assign values to


data members.

Object Oriented Programming Brief Introduction


Classes and instances

Default constructor

It should be noted that a default constructor (without any


parameters) is pre-defined for you by Java and thats why you can
instantiate objects without defining it yourself.
1

R e c t a n g e r = new R e c t a n g l e ( ) ;

The default constructor assigns the default values for the


appropriate data types to the instance variables. However, once
you define a parameterized constructor, the built-in default
constructor is taken away by Java. Thus, if you want to construct
an object with default initial values for the instance variables, you
need to re-define that!

Object Oriented Programming Brief Introduction


Classes and instances

Defining the default constructor

Lets say the default rectangle should be of unit length. We can


define the default constructor as,
1
2
3
4

public Rectangle () {
setLength (1) ;
setBreadth (1) ;
}

Object Oriented Programming Brief Introduction


Classes and instances

Exercise - Add a default and parameterized constructor

v EXERCISE TIME! w
Add two constructors to the class Circle.
1
No parameters passed (default constructor): Assigns the
value 0.3183099 to radius ... through the setter (who can
tell me why this value?)
2
Parameter passed for radius (parameterized constructor):
Assigns the passed value to radius through the setter.

Object Oriented Programming Brief Introduction


Classes and instances

Displaying objects

Often we need to display the details of an object. For example, we


might need to display name and age of a Person object, or the
details of a Time object in the format hours:minutes:seconds,
or in our example, width and height of a Rectangle object. It is
quite inconvenient to display these details as,
1
2

R e c t a g l e r e c t = new R e c t a n g l e ( 5 , 8 ) ;
System . o u t . p r i n t l n ( r e c t . w i d t h + by +r e c t
. height ) ;

Object Oriented Programming Brief Introduction


Classes and instances

Displaying objects

We could add a method display in the class Rectangle as,


1
2

public void d i s p l a y ( ) {
System . o u t . p r i n t l n ( w i d t h + by +
height ) ;
}

And call this method on required object as,


1
2

R e c t a g l e r e c t = new R e c t a n g l e ( 5 , 8 ) ;
rect . display () ;

Object Oriented Programming Brief Introduction


Classes and instances

Problem with the display() method

But this would only let us display the object details, and not send
to a file, or concatenate with any other output.
Java provides a standard way to return the String description of an
object using the toString() method (with return type String).

Object Oriented Programming Brief Introduction


Classes and instances

Default toString() behaviour


When you display an object, what Java displays is the outcome of
the toString() method on that object
1

R e c t a n g l e m y R e c t a n g l e = new R e c t a n g l e ( 1 , 3 )
;
System . o u t . p r i n t l n ( m y R e c t a n g l e ) ; //
something l i k e [ I@70dea4e

Java saw that you want to display a rectangle object and replaced
it by the toString() method operating on that object as,
1
2
3

System . o u t . p r i n t l n ( m y R e c t a n g l e ) ;
// became
System . o u t . p r i n t l n ( m y R e c t a n g l e . t o S t r i n g ( ) ) ;

Object Oriented Programming Brief Introduction


Classes and instances

Over-riding toString() behaviour


We can over-ride toString() method as required. For the
Rectangle class,
1
2
3

public String toString () {


r e t u r n w i d t h + by +h e i g h t ;
}

When we display an object, it invokes the method toString()


and displays the value it returns.
1
2
3

R e c t a g l e m y R e c t a n g l e = new R e c t a n g l e ( 5 , 8 ) ;
System . o u t . p r i n t l n ( m y R e c t a n g l e ) ;
// a u t o m a t i c a l l y i n v o k e s m y R e c t a n g l e .
t o S t r i n g ( ) and d i s p l a y s t h e v a l u e
returned

Object Oriented Programming Brief Introduction


Classes and instances

Exercise - Define toString method

v EXERCISE TIME! w
Define the toString method in the Circle class such that it
displays the object details in the following format Circle radius: <radius>, area: <area>
In a separate client, create a Circle object with radius 1.6 and
display it on the console.

Vous aimerez peut-être aussi