Vous êtes sur la page 1sur 37

Object Life Cycle

You create an object from a class by using:


the new operator, and
a constructor

Instance variables and methods can be


accessed by:
qualified names
objectReference.variableName
that refers to the current object
objectReference.methodName(argumentList)

Note : this is a Java language keyword


1

Object Life Cycle (Contd)


The Garbage Collector automatically cleans
up unused objects
an object is unused if the program holds no more
references to it.

In some situations, you may want to run the


garbage collection explicitly by calling the gc
method in the java.lang.System class.
You can explicitly drop a reference by setting the
variable holding the reference to null.
2

Creating Classes

Creating Classes -Class Declaration

Creating Classes -Class Declaration


Minimum needed
AccessLevel

Indicates the access level for this class

Class
nameOfClass

Declares a class with a name


nameOfClass should be a valid identifier

{
ClassBody
}

Class Declaration
Access Level
By default, a class can be used only by
other classes in the same package.
Look in Creating and Using Packages for
information about how to use modifiers to
limit access to your classes and how it
affects your access to other classes.
6

Class Body
The class body contains all of the code that
provides for the life cycle of the objects created
from it:
constructors for initializing new objects,
declarations for the member attributes that provide
the state of the class and its objects,
Member methods to implement the behavior of the
class and its objects

Variables and methods collectively are called


members.
7

Object state
The idea of "state" is that an object has
characteristics that it keeps as long as it
exists. The characteristics may change in
value during the lifetime of the object.
The state of an object is held in its
instance variables (not class variables, not
in the parameters of methods, nor in the
local variables of methods.)
8

Object state example


class mpgTester
{
public static void main ( String[] args )
{
Car myCar = new Car( 12000, 12340, 12.3 );
. . . . . .
}
}

The state of the object is set to:


startMiles = 12000
endMiles = 12340
gallons = 12.3
The object referenced by myCar holds these values as long as it exists.
9

Class Body -- Constructors


Constructors are not methods. Nor are they members.
All Java classes have constructors that are used to initialize a new
object of that type.
A constructor has the same name as the class.
Java supports name overloading for constructors so that a class
can have any number of constructors, all of which have the same
name.
The compiler differentiates these constructors based on the
number of parameters in the list and their types.
Typically, a constructor uses its arguments to initialize the new
object's state. When creating an object, choose the constructor
whose arguments best reflect how you want to initialize the new
object.
10

Class Body -- Constructors


The default constructor is automatically provided by the
runtime system for any class that contains no constructors:
But it doesn't do anything. So, if you want to perform some
initialization, you will have to write some constructors for your
class.

The body of a constructor is like the body of a method; that


is, it contains local variable declarations, loops, and other
statements.

You can specify what other objects can create instances of


your class by using an access level in the constructors'
declaration
11

Class Body-Declaring Member Variables


(minimum needed)
AccessLevel

Indicates the access level for this


variable

static

Declares a class member

final

Indicates that it constant

type name

The type and the name of the


variable
12

Creating Classes-Class Body


(Declaring Member Variables)
accessLevel
Lets you control which other classes have
access to a member variable by using one of
four access levels: public, protected, package,
and private. You control access to methods in
the same way.

final
Indicates that the value of this member cannot
change.
13

Creating Classes-Class Body


(Declaring Member Variables)
Instance variables: When you declare a member variable
in a class you declare an instance variable.
Every time you create an instance of a class, the runtime
system creates one copy of each class's instance variables
for the instance.
You can access an object's instance variables only from an
object.

Static or Class variables:


Class variables are declared using the static modifier.

The runtime system allocates class variables once per class


All instances share the same copy of the class's class
variables.
You can access class variables through an instance or
through the class itself.
14

Static variables
Example
public class StaticExample
public static int x;
public int y;

e2

e1

public StaticExample (int a, int b) {


x = a;
y = b;
}
public void incr() {
x++;
y++;
e1 object
}
allocation
}
public static void main (String
args[]) {
StaticExample e1 = new
StaticExample(5, 10);
StaticExample e2 = new
StaticExample(12, 7);
e1.incr();

10

e2 object
allocation

12
Class
allocation
15

Example
public class Bicycle{
private
private
private
private

int cadence;
int speed;
int id;
static int numberOfBicycles = 0;

public Bicycle (int startCadence, int startSpeed){


cadence = startCadence;
speed = startSpeed;
// increment number of Bicycles and assign ID number
id = ++numberOfBicycles;
}
public static void main( String args[]) {
Bicycle b1 = new Bicycle (12, 15);
Bicycle b2 = new Bicycle (10, 25);
System.out.println(total bicycles:+
Bicycle.numberOfBicycles );
}
}
16

Class Body-Declaring Methods

17

Class Body-Declaring Methods


(minimum needed)
AccessLevel

Indicates the access level for this


method

static

Declares a method as a class


method

returnType
methodName

The return type and the method


name

(paramlist)

The list of arguments

Throws
exceptions

The exceptions thrown by this


method (to be discussed in chapter 5)
18

Creating Classes Class Body


Declaring Methods
accessLevel
As with member variables, you control which
other classes have access to a method using
one of four access levels: public, protected,
package, and private

19

Creating Classes Class Body


Declaring Methods
Your classes can have instance methods and class methods.
Instance methods operate on the current object's instance
variables but also have access to the class variables.
Class methods cannot access the instance variables declared
within the class (unless they create a new object and access
them through the object).
Also, class methods can be invoked on the class, you don't
need an instance to call a class method.
Their implementation is independent on the state of the object
20

Packages
A package is a collection of related
classes and interfaces providing access
protection and namespace management:
Help know where to find groups of related
classes and interfaces.
Avoid conflict with class names in other
packages, because the package creates a
new namespace.
21

Packages
How to create a package?
// only comment can be here
package world;
public class HelloWorld {
public String sayHello() {
return Hello World;
}
}
Note: packages should map to file system, for package world you should
create directory world that contains HelloWorld class definition
22

PackagesUsing Package Members


1. Declare the fully-qualified class name.
world.HelloWorld helloWorld =
new world.HelloWorld();

2. Use an "import" keyword:


import world.*;
HelloWorld hello = new HelloWorld();
// don't have to explicitly specify
// world.HelloWorld anymore

Note: You might have to set your class path so that the
compiler and the interpreter can find the source and
class files for your classes and interfaces

23

PackagesDisambiguating a Name
If a member in one package shares the same name with a member in
another package and both packages are imported, you must refer to
each member by its qualified name.
For exmaple lets define the following
package graphics;
public class Rectangle { . . . }
The java.awt package also contains a Rectangle class. If both graphics
and java.awt have been imported, the following is ambiguous:
Rectangle rect;
In such a situation, you have to be more specific and use the member's
qualified name to indicate exactly which Rectangle class you want:
graphics.Rectangle rect; or
Java.awt.Rectangle rect;
24

Creating Classes Class Body


(Controlling access to members of a Class )
Specifier

Class Subclass Package

private

protected

public

Package(1)

World

(1) you dont explicitly set a members access level to one of the other levels25

Access Control -- Private


Private:
The most restrictive access level is private. A private
member is accessible only to the class in which it is
defined
This includes variables that contain information that if
accessed by an outsider could put the object in an
inconsistent state
But objects of the same type have access to one
another's private members

26

Access Control -- Private


class Alpha {
private int iamprivate;
private void privateMethod() {
System.out.println("privateMethod");
}
}
class Beta {
void accessMethod() {
Alpha a = new Alpha();
a.iamprivate = 10; // illegal
a.privateMethod(); // illegal
}
}
27

Access Control--Protected
Protected
allows the class itself, subclasses and all classes in
the same package to access the members.
Use the protected access level when it's appropriate
for a class's subclasses to have access to the
member, but not unrelated classes.
Protected members are like family secrets--you don't
mind if the whole family knows, and even a few
trusted friends but you wouldn't want any outsiders to
know.
28

Access Control--Protected
package Greek;
public class Alpha {
protected int iamprotected;
protected void protectedMethod() {
System.out.println("protectedMethod");
}
}
class Gamma {
void accessMethod() {
Alpha a = new Alpha();
a.iamprotected = 10;
// legal
a.protectedMethod();
// legal
}
}
29

Access Control--Protected
package greek;
public class Alpha {
protected int iamprotected;
protected void protectedMethod() {
System.out.println("protectedMethod");
}
}
package roman;
import greek.Alpha; //needed only to find
//the symbol Alpha
class Gamma extends Alpha {
void accessMethod() {
Alpha a = new Alpha();
a.iamprotected = 10;
// legal
a.protectedMethod();
// legal
}
}

30

Access Control -- Public


Public
Any class, in any package, has access to a
class's public members.
Declare public members only if such access
cannot produce undesirable results if an
outsider uses them.
There are no personal or family secrets here;
this is for stuff you don't mind anybody else
knowing.
31

Access Control -- Public


package Greek;
public class Alpha {
public int iampublic;
public void publicMethod() {
System.out.println("publicMethod");
}
}
package Roman;
import Greek.*;
class Beta {
void accessMethod() {
Alpha a = new Alpha();
a.iampublic = 10;
a.publicMethod();
}
}

// legal
// legal
32

Access Control -- Package


Package
The package access level is what you get if you don't
explicitly set a member's access to one of the other
levels.
This access level allows classes in the same package
as your class to access the members.
This level of access assumes that classes in the
same package are trusted friends. This level of trust is
like that which you extend to your closest friends but
wouldn't trust even to your family.
33

Access Control -- Package


package Greek;
class Alpha {
int iampackage; //package access level by default
void packageMethod() {
System.out.println("packageMethod");
}
}
package Greek;
class Beta {
void accessMethod() {
Alpha a = new Alpha();
a.iampackage = 10;
// legal
a.packageMethod();
// legal
}
}

34

Access Control -- Package


package Greek;
class Alpha {
int iampackage; //package access level by default
void packageMethod() {
System.out.println("packageMethod");
}
}
package Roman;
import Greek.Alpha;
class Beta {
void accessMethod() {
Alpha a = new Alpha();
a.iampackage = 10;
// illegal
a.packageMethod();
// illegal
}
}

35

Access Control -- Package


package Greek;
class Alpha {
int iampackage; //package access level by default
void packageMethod() {
System.out.println("packageMethod");
}
}
package Roman;
import Greek.Alpha;
class Beta extends Alpha{
void accessMethod() {
Alpha a = new Alpha();
a.iampackage = 10;
// illegal
a.packageMethod();
// illegal
}
}

36

References on the Web


http://java.sun.com/docs/books/tutorial/java/int
erpack/packages.html

http://java.sun.com/docs/books/tutorial/java/jav
aOO/classes.html

http://java.sun.com/docs/books/tutorial/java/jav
aOO/classvars.html
37

Vous aimerez peut-être aussi