37
1 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

Ch3_Java Basics II - Objects & Classes (JABA1)

Embed Size (px)

DESCRIPTION

jAva basics

Citation preview

Page 1: Ch3_Java Basics II - Objects & Classes (JABA1)

1

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

Page 2: Ch3_Java Basics II - Objects & Classes (JABA1)

2

Object Life Cycle (Cont’d)

• 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.

Page 3: Ch3_Java Basics II - Objects & Classes (JABA1)

3

Creating Classes

Page 4: Ch3_Java Basics II - Objects & Classes (JABA1)

4

Creating Classes -Class Declaration

Page 5: Ch3_Java Basics II - Objects & Classes (JABA1)

5

Creating Classes -Class DeclarationMinimum needed

AccessLevel Indicates the access level for this class

Class nameOfClass

Declares a class with a namenameOfClass should be a valid identifier

{ ClassBody}

Page 6: Ch3_Java Basics II - Objects & Classes (JABA1)

6

Class DeclarationAccess 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.

Page 7: Ch3_Java Basics II - Objects & Classes (JABA1)

7

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.

Page 8: Ch3_Java Basics II - Objects & Classes (JABA1)

8

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.)

Page 9: Ch3_Java Basics II - Objects & Classes (JABA1)

9

Object state exampleclass 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.

Page 10: Ch3_Java Basics II - Objects & Classes (JABA1)

10

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.

Page 11: Ch3_Java Basics II - Objects & Classes (JABA1)

11

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

Page 12: Ch3_Java Basics II - Objects & Classes (JABA1)

12

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

Page 13: Ch3_Java Basics II - Objects & Classes (JABA1)

13

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.

Page 14: Ch3_Java Basics II - Objects & Classes (JABA1)

14

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.

Page 15: Ch3_Java Basics II - Objects & Classes (JABA1)

15

Static variablesExample

public class StaticExample {public static int x;public int y;

public StaticExample (int a, int b) {x = a;y = b;

}public void incr() {

x++;y++;

}}public static void main (String

args[]) {StaticExample e1 = new StaticExample(5, 10); StaticExample e2 = new StaticExample(12, 7);e1.incr();

y y

e1

7

e2

10

5x 12

e2 object allocation

e1 object allocation

Class allocation

Page 16: Ch3_Java Basics II - Objects & Classes (JABA1)

16

Examplepublic class Bicycle{

private int cadence; private int speed;

private int id; private 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 );

}}

Page 17: Ch3_Java Basics II - Objects & Classes (JABA1)

17

Class Body-Declaring Methods

Page 18: Ch3_Java Basics II - Objects & Classes (JABA1)

18

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)

Page 19: Ch3_Java Basics II - Objects & Classes (JABA1)

19

Creating Classes – Class BodyDeclaring 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

Page 20: Ch3_Java Basics II - Objects & Classes (JABA1)

20

Creating Classes – Class BodyDeclaring 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

Page 21: Ch3_Java Basics II - Objects & Classes (JABA1)

21

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.

Page 22: Ch3_Java Basics II - Objects & Classes (JABA1)

22

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

Page 23: Ch3_Java Basics II - Objects & Classes (JABA1)

23

Packages- Using 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

Page 24: Ch3_Java Basics II - Objects & Classes (JABA1)

24

Packages- Disambiguating 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 let’s define the followingpackage 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; orJava.awt.Rectangle rect;

Page 25: Ch3_Java Basics II - Objects & Classes (JABA1)

25

Creating Classes – Class Body(Controlling access to members of a Class)

Specifier Class Subclass Package World

private x

protected x x x

public x x x x

Package(1) x x

(1) you don’t explicitly set a member’s access level to one of the other levels

Page 26: Ch3_Java Basics II - Objects & Classes (JABA1)

26

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

Page 27: Ch3_Java Basics II - Objects & Classes (JABA1)

27

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

} }

Page 28: Ch3_Java Basics II - Objects & Classes (JABA1)

28

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.

Page 29: Ch3_Java Basics II - Objects & Classes (JABA1)

29

Access Control--Protectedpackage 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 }}

Page 30: Ch3_Java Basics II - Objects & Classes (JABA1)

30

Access Control--Protectedpackage 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 Alphaclass Gamma extends Alpha { void accessMethod() { Alpha a = new Alpha(); a.iamprotected = 10; // legal a.protectedMethod(); // legal }}

Page 31: Ch3_Java Basics II - Objects & Classes (JABA1)

31

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.

Page 32: Ch3_Java Basics II - Objects & Classes (JABA1)

32

Access Control -- Publicpackage 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; // legal a.publicMethod(); // legal }}

Page 33: Ch3_Java Basics II - Objects & Classes (JABA1)

33

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.

Page 34: Ch3_Java Basics II - Objects & Classes (JABA1)

34

Access Control -- Packagepackage 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 }}

Page 35: Ch3_Java Basics II - Objects & Classes (JABA1)

35

Access Control -- Packagepackage 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 }}

Page 36: Ch3_Java Basics II - Objects & Classes (JABA1)

36

Access Control -- Packagepackage 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 }}