03 OOP_Lecture#3
03 OOP_Lecture#3
8 من1 الصفحة
8 من2 الصفحة
8 من2 الصفحة
8 من3 الصفحة
o The presence of the main method in the class makes the class
executable.
The new operator is used to create an object from the class using the
appropriate constructor:
o new Circle () creates an object with radius 1, new Circle (25)
creates an object with radius 25, and new Circle (125) creates an
object with radius 125.
o These three objects (referenced by circle1, circle2, and circle3)
have different data but the same methods. Therefore, you can
compute their respective areas by using the getArea () method.
o The data fields can be accessed via the reference of the object
using circle1.radius, circle2.radius, and circle3.radius,
respectively.
Class.java1 Listing
8 من3 الصفحة
8 من4 الصفحة
Listing2 . CircleTest.java
8 من4 الصفحة
8 من5 الصفحة
For example, new Circle () creates an object of the Circle class using the first
constructor defined in the Circle class, and new Circle (25) creates an object
using the second constructor defined in the Circle class.
Aclass normally provides a constructor without arguments (e.g., Circle ()).
Such a constructor is referred to as a no-arg or no-argument constructor.
A class may be defined without constructors. In this case, a public no-arg
constructor with an empty body is implicitly defined in the class. This
constructor, called a default constructor, is provided automatically only if no
constructors are explicitly defined in the class
8 من5 الصفحة
8 من6 الصفحة
The variable myCircle can reference a Circle object. The next statement
creates an object and assigns its reference to myCircle:
You can write a single statement that combines the declaration of an object
reference variable, the creation of an object, and the assigning of an object
reference to the variable with the following syntax:
Here is an example:
8 من6 الصفحة
8 من7 الصفحة
Figure 3. A variable of a primitive type holds a value of the primitive type, and a
variable of a reference type holds a reference to where an object is stored in memory
When you assign one variable to another, the other variable is set to the same
value. For a variable of a primitive type, the real value of one variable is
assigned to the other variable. For a variable of a reference type, the
reference of one variable is assigned to the other variable. As shown in
8 من7 الصفحة
8 من8 الصفحة
8 من8 الصفحة