java_2_object_classes_interfaces_packages_annotations.pdf

(2388 KB) Pobierz
„Objects
classes, interfaces, packages, annotations”
Objects classes, interfaces, packages,
annotations
Creating Objects
Each
statement
has three parts:
1.Declaration:
When you create an object, you do not have to
declare a variable to refer to it. However, a variable declaration
often appears on the same line as the code to create an object.
2.Instantiation:
new is a Java operator that creates the new
object (allocates space for it).
3.Initialization:
The new operator is followed by a call to a
constructor. For example, Point(23, 94) is a call to Point's only
constructor. The constructor initializes the new object.
Objects classes, interfaces, packages,
annotations
Creating Objects(2)
1) Declaration
type name
Declarations do not create new objects.
The code
Point
origin_one
does not create a new
Point object;
it just
declares a variable, named
origin_one,
that will be used to
refer to a
Point
object. The reference is empty until assigned.
An empty reference is known as a
null reference.
To create an object you must instantiate it with the
new
operator.
Objects classes, interfaces, packages,
annotations
Creating Objects(3)
2) Instantiating an object
The
new
operator instantiates a class by allocating
memory for a new object. The
new
operator requires a
single, postfix argument: a call to a constructor. The name of
the constructor provides the name of the class to instantiate.
The constructor initializes the new object.
The
new
operator returns a reference to the object it
created. Often, this reference is assigned to a variable of the
appropriate type. If the reference is not assigned to a
variable, the object is unreachable after the statement in
which the
new
operator appears finishes executing.
Objects classes, interfaces, packages,
annotations
Creating Objects(4)
3) Intializing an object
Example:
public class Point {
Point origin_one =
public int x = 0;
public int y = 0;
public Point(int x, int y) {
this.x = x;
this.y = y;
new Point(23, 94);
}
}
Zgłoś jeśli naruszono regulamin