Upload
soufiane-elabed
View
7
Download
2
Embed Size (px)
DESCRIPTION
jAva basics
Citation preview
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
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.
3
Creating Classes
4
Creating Classes -Class Declaration
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}
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.
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.
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.)
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.
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.
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
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
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.
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.
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
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 );
}}
17
Class Body-Declaring Methods
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)
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
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
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.
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
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
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;
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
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
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
} }
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.
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 }}
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 }}
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.
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 }}
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.
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 }}
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 }}
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 }}
37
References on the Web
• http://java.sun.com/docs/books/tutorial/java/interpack/packages.html
• http://java.sun.com/docs/books/tutorial/java/javaOO/classes.html
• http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html