Anda di halaman 1dari 7

Software Development 2 Bell College 5. Creating Objects page 1 5: CREATING OBJECTS Lifecycle of an Object .....................................................................................................

1 Creating Objects: BlueJ .................................................................................................1 EXERCISE: Creating Objects: BlueJ .............................................................................9 Creating Objects: Code ................................................................................................11 EXERCISE: Creating Objects: Code............................................................................13 Garbage Collection .......................................................................................................14 EXERCISE: Questions on Object creation..................................................................14 Lifecycle of an Object A typical Java program creates many objects which interact with each other by sending messages. Through these interactions the program implements the required functionality. Each object is an instance of a class. Once an object has completed its task, its resources are recycled for other objects to use. Creating Objects: BlueJ You have already used BlueJ to create instances of classes displayed in the BlueJ class diagram. You have created objects, called their methods and inspected their properties. Creation of an object from a class needs three key stages: DECLARATION: Declare a variable. The variable type is the name of the class. Declaration on its own does not create an object it creates an object reference, which is a null reference until it is assigned to an instance. Example after declaration of a variable point1 of a class Point which represents a position on a coordinate diagram. point1 (null reference) Software Development 2 Bell College 5. Creating Objects page 2 INSTANTATION: Create an instance and assign this instance to the variable. The key word associated with instantiation is new. point1 INITIALISATION: Set up the initial state of the instance by calling a constructor. point1 new Point Point x=4 y=5 x y Software Development 2 Bell College 5. Creating Objects page 3 Example classes We will look at objects using the following classes which represent a circle and a point on a coordinate diagram.

Circle /** * Circle - represents a circle * * @author (yourname) * @version 1.0 */ public class Circle { // instance variables public Point centre; public int radius = 0; /** * Default constructor */ public Circle() { centre = new Point(0,0); } /** * Constructor using a Point */ public Circle(Point p) { centre = p; } /** * Constructor using a Point and integer value */ public Circle(Point p, int r) { centre = p; radius = r; } Software Development 2 Bell College 5. Creating Objects page 4 /** * Constructor using an integer value for radius */ public Circle(int r) { this(new Point(0,0), r); } /** * A method for moving the circle *

* @param x distance moved horizontally * @param y distance moved vertically */ public void move(int x, int y) { centre.x += x; centre.y += y; } /** * A method to compute the area of the circle * * @return the area */ public double area() { return 3.14159 * radius * radius; } } Software Development 2 Bell College 5. Creating Objects page 5 Point /** * Point - represents a point * * @author (yourname) * @version 1.0 */ public class Point { // instance variables public int x = 0; public int y = 0; /** * Constructor for objects of class Point */ public Point(int x, int y) { this.x = x; this.y = y; } } Software Development 2 Bell College 5. Creating Objects page 6 Constructors A constructor is a special method which sets the initial state of an object when it is created.

A class can have more than one constructor so that instances can be initialised in different ways. For example, a Circle object can be initialised in the following ways: by using default values for the centre and the radius by specifying the centre and using a default value for the radius by specifying the centre and radius by specifying the radius and using a default value for the centre Constructors are methods which have the same name as the class. For example: /** * Default constructor */ public Circle() { centre = new Point(0,0); } Look at the code above and identify the other constructors for the Circle class. Creating an object in BlueJ To create an instance of the Circle class, you right-click the class in the BlueJ class diagram and select new Circle. This is the Instantiation stage. When there is more than one constructor, all the available options are shown in the pop-up menu. Software Development 2 Bell College 5. Creating Objects page 7 If you select new Circle(r), for example, you will then see the following dialog: This allows you to specify the name of the object (Declaration) and the parameter to be supplied to the constructor (Initialisation). Here, the constructor which is called is the one which requires a value for the radius, and uses a default value for the centre. public Circle(int r){ } The Point class has a single constructor which requires two integer values to specify the coordinates of the point. Calling a method in BlueJ To call a method of an object, you right-click on the instance and select the method from the pop-up menu. Software Development 2 Bell College 5. Creating Objects page 8 Objects which contain objects A Circle object has two member variables an integer which represents the radius and a Point object which represents the centre. If a Circle is initialised by specifying the centre, then this Point object must be created first. This can be done in BlueJ in two ways: 1. Create the Point object first, then assign it to the centre of the Circle 2. Instantiate a new Point object using the expression new Point(x,y) Software Development 2 Bell College 5. Creating Objects page 9 An object can have multiple references to it. In the first case above, point_1 and circle_1.centre are references to the same Point object.

point_1 EXERCISE: Creating Objects: BlueJ Create a new BlueJ project called createobjects. Add the Circle and Point classes using the code given above. The project window should look like this Point x=4 y=5 Circle centre r=5 Software Development 2 Bell College 5. Creating Objects page 10 1. Create a Point object called point1 with coordinates (4,5). Inspect the object point1. Create a Circle object called circle_1 with radius 10. Inspect the object circle1. What are the coordinates of the centre of circle1 Find the area of circle1 2. Create a Circle object called circle2 with radius 5 and point1 as its centre. Inspect the object circle2 What are the coordinates of the centre of circle2 Find the area of circle2 3. Create a Circle object called circle3 with radius 3 and centre (3,4). Inspect the object circle3. What are the coordinates of the centre of circle3 Find the area of circle3 4. Inspect circle2. Select the centre object reference and click the Get button. Choose centre as the new object name. circle2s centre object now appears as an instance alongside circle2, etc. Call a method of circle2 to shift the centre of the circle by 2 units in both directions. Inspect centre. Also inspect point1 What are the coordinates of the centre of circle2 now? What are the coordinates of point1 now? Explain your answer Software Development 2 Bell College 5. Creating Objects page 11 Creating Objects: Code Creating objects in BlueJ is useful for testing and understanding classes. However, programs usually need to create objects as they run. This is done using Java statements. The Circle class contains code to create new Point objects. For example: public Point centre; centre = new Point(0,0); These statements follow the three key stages of object creation: DECLARATION:

public Point centre; declares a new variable of type Point. INSTANTATION: centre = new Point Create an instance using the new. Keyword, and assign this instance to the variable. INITIALISATION: new Point(0,0); Set up the initial state of the instance by calling a constructor. In the Circle class, the code to create a new Point is inside a constructor of Circle. This means that as a new Circle object is created, it in turn creates a new Point object if necessary. It is necessary to do this if no new Point object is specified to be the centre of the circle. The three stages can also be done in a single statement, for example: Circle circle_1 = new Circle(5); Software Development 2 Bell College 5. Creating Objects page 12 Creating a test program Rather than using BlueJ to create objects directly, you can write a test program which creates and inspects objects in your project. Essentially this means writing a main method. The main method can be inside an existing class, or can be placed in a separate test class. For example, the following test program creates a Point and a Circle, and inspects the Circles state. /** * CreateObjectTest - a test program for Circle and Point * * @author (yourname) * @version 1.0 */ public class CreateObjectTest { public static void main(String[] args) { //declare a point and a circle Circle circle_1 = new Circle(10); //display circle_1's centre and radius System.out.println("Centre: (" + circle_1.centre.x + ", " + circle_1.centre.y + ")"); System.out.println("Radius: " + circle_1.radius); //display circle_1's area System.out.println("Area: " + circle_1.area()); } } Inpsecting variables To inspect the value of a simple member variable of an object, you need to output the value using dot notation like this

circle_1.radius To inspect the value of a member variable which is itself an object, you need to output the value using another level of dot notation like this circle_1.centre.x Software Development 2 Bell College 5. Creating Objects page 13 Calling methods To call a method of an object, you need to use dot notation like this circle_1.area() EXERCISE: Creating Objects: Code Add the above CreateObjectTest to your project and run the main method. Modify the test program to create the same objects as the previous exercise, inspect the same variables and call the same methods. Software Development 2 Bell College 5. Creating Objects page 14 Garbage Collection Some object-oriented languages require that you keep track of all the objects you create and that you explicitly destroy them when they are no longer needed, i.e. when no reference to them exists. The Java runtime environment, on the other hand, has a garbage collector which automatically frees memory used by objects that are no longer referenced. EXERCISE: Questions on Object creation 1. The following program has something wrong: public class SomethingWrong { public static void main(String[] args) { Circle myCirc; myCirc.radius = 20; System.out.println("area is " + myCirc.area()); } } Identify the error Add this class to your project and fix the error 2. The following code creates two Point objects and one Circle object. Point point_1 = new Point(5,5); Point point_2 = new Point(7,8); Circle circle_1 = new Circle(point_2, 10); point_1 = null; point_2 = null; How many object references exist after this code has executed? Why? Which object(s) are eligible for garbage collection?

Anda mungkin juga menyukai