Chapter 1



Lessons 4 – 5

Objects and Classes

Part II

Objectives

• To understand the concepts of Objects and Classes as they pertain to the subject Object Oriented Programming.

• To understand the relationship between Objects and Classes.

• To learn how to define a class in terms of its name, variables, methods, and constructors.

• To differentiate between class variables and instance variables.

• Be able to define constants.

• To understand the difference between class methods and instance methods.

• To learn how to create objects of a class.

• To learn how to call instance methods.

• To learn how to call class methods.

• To understand what access attributes are and how to use them in a class.

• To be acquainted with the concept of Java Garbage collection mechanism, and what role its plays in a program.

More On Classes and Objects

We have just seen how to define classes to describe a particular entity. We have also seen to how define test class that is used to create instances and to call methods of another class. There are more features for defining classes and we will study them in the remaining sections of this lesson. We begin by discussing the concept of local variables and their scope within the class. We will also study modifiers in more depth. This will be followed by discussion on method overloading and how to call member methods from within the class itself. We will also study default constructor and constructor overloading. We will also learn about the reference object called this and its function within the class. Finally, we will discuss the concept of Garbage Collection.

Scope of Local Variables

Local variables, also called automatic variables, are variables that are declared within methods, constructors, and blocks of codes. A block is any body of code that is enclosed inside the method definition, including constructors, and within pair of curly braces. Formal parameters are also considered local variables. These variables are called local because they cannot be accessed outside of their confinement. Unlike member variables, local variables must be initialized before they can be used. Consider Listing 2.12, Line 5 shows the declaration of the local variable, and Line 6 shows its usage. This local variable has been declared but was not initialized, hence the actual compilation error is shown in Figure 2.12.

1. class localVariables

2. {

3. public localVariables()

4. {

5. int localVariable;

6. System.out.println("Local variable = " + localVariable);

7. }

8. }

Listing 2.12 Local variable declared but not initialized before it is used.

Notice that the compiler complains about the variable localVariable. Specifically it points out that the variable has not been initialized.

C:\Documents and Settings\Administrator\My Documents\Manuscript\manuscript2003\Listings\exercise2j\

localVariables.java:7: variable localVariable might not have been

initialized

System.out.println("Local variable = " + localVariable);

^

1 error

Process completed with exit code 1

Figure 2.12 The actual compilation error stating that the local variable has not been initialized before using it.

Let us resolve this and initialize the variable. However, let us add a method to the class. This time have the method attempting to access the local variable declared in the constructor. See Listing 2.13. Line 5 shows the declaration and initialization of the local variable, and Line 10 shows the attempted use of the variable. Figure 2.14 shows the actual compilation error.

1. class localVariables

2. {

3. public localVariables()

4. {

5. int localVariable = 10;

6. }

7.

8. void aMethod()

9. {

10. System.out.println("Local variable = " + localVariable);

11. }

12. }

Listing 2.13 Local variable attempted to be used outside of its scope.

This time notice that the compiler cannot find a declaration for the variable that is used in Line 10, hence it says that it cannot resolve the symbol, localVariable.

C:\Documents and Settings\Administrator\My Documents\Manuscript\manuscript2003\Listings\

exercise2j\localVariables.java:13: cannot resolve symbol

symbol : variable localVariable

location: class localVariables

System.out.println("Local variable = " + localVariable);

^

1 error

Process completed with exit code 1

Figure 2.14 Actual compilation error stating that the local variable has not been

declared within the cope of its usage.

Listing 2.14 below shows that the local variable is declared within the pair of curly, which makes this variable local to the segment. An attempt has been made to access it outside of the curly braces. This construct generate error message similar to the result of Listing 2.14.

1. class localVariables

2. {

3. public localVariables()

4. {

5. {

6. int localVariable = 10;

7. }

8.

9. System.out.println("Local variable = " + localVariable);

10. }

11. }

Listing 2.14 Local variable declared within curly braces, and is attempted to be used outside its confinement.

Local variables are instantiated for each invocation of the method or the block. A block is any segment of codes that is enclosed within a pair of curly braces. You cannot apply any of the access specifiers (private, protected, public) for visibility to local variables. They are not accessible outside of the block; they are only accessible within the block in which they are declared.

Local variable are called automatic variable because by default they automatically take the attribute of their method. If the method is a class method, they are automatically class variables. Similarly, if they are declared inside instance methods they are automatically instance variables. As a result these variables are never qualified as private, protected, or public. Similarly, if the are declared inside a class method, they are not declared with the keyword static.

Modifiers

We have discussed three modifiers so far. These are private, final and static. Now we will discuss protected, and public. As we have mentioned earlier, the concept of encapsulation is one of the major features of Object Oriented Programming. That is, in order to define a class properly, you need to ensure that access to its data fields and methods is controlled. This means that we should ensure what fields can be accessed inside or outside of the class. This feature is called encapsulation. One way of implementing encapsulation is by using modifiers.

In this section we will discuss modifiers as they pertain to the scope of variables. Modifiers specify the scope of member variables and member methods of a class; that is, the extent to which either of them can be accessed. We will start with the modifier public first.

public - When a variable or a method is declared public, the declaration signifies that any class can access the variable or the method.

protected - When a variable is declared protected, the declaration signifies that only certain classes can refer to this variable or method. It is used in the context of inheritance, which is beyond the scope of this course.

A good guide is to make all variables private and access them through methods with public access specifier. If you are certain that you want to expose them to other classes then you can make them public.

Exercises (2i)

1. Where are local variables declared? Write a segment of code say a constructor or a method, and give two examples of local variables in it.

2. Where can you refer to a local variable without it generating syntax error? Demonstrate this in Exercise 1.

3. Which of the following statements are true? Select all valid answers.

a) Private member variables can only be accessed by code from within the class of the member.

b) Local variables can be accessed by code from outside of its scope.

c) A local variable that is declare the public assess specifier can be accessed by code from outside of its scope.

d) Public member methods can be accessed from outside the class from which they are defined.

e) Private member methods can be accessed from outside the class that they are defined.

f) Some local variables must be initialized before it can be used.

g) It is illegal to specify visibility to local variables.

4. The following class definition has syntax errors. Identify as many as you can and correct them. Type the class as given, compile it and compare your answer to that of the compiler. Next, make the necessary corrections to the code you typed. Compile it again. Repeat until all errors are eliminated.

class localVariables

{

public localVariables(int local)

{

int localVariable;

System.out.println("Local variable = " +

localVariable);

}

public void memberMethod1(int local)

{

{

int localVariable = local;

}

System.out.println("Local variable = " +

localVariable);

}

public void memberMethod2()

{

System.out.println("Local variable = " + local);

}

}

Method Overloading

In Java the concept of polymorphism is central to Object Oriented Programming. One of the attributes of a polymorphic system is for the system or member, of the system to exhibit different behavior. For example, in the real world, the act of driving a motorcar or driving a lorry is a polymorphic behavior. The pocket calculator exhibits polymorphism, because can be use to multiply two integers, to multiply two floating-point values, or a combination of both types of numbers. These two examples illustrate the concept of method overloading. In the first case the method of driving addresses two different kinds of vehicles. In the second case the method of multiplying uses different data values, and the calculator knows exactly how to react to the different types of data values.

Method overloading is the concept of a named method to have two or more definitions within the same class. That is, each method has a signature, which comprises the name of the method, the types of parameters, and the parameter list. This is an acceptable feature in most Object Oriented Programming languages, and Java is no exception. As long as there are no ambiguities in the definition of each method, then method overloading works fine. Ambiguity can be avoided if you know the rules governing the overloading of methods. The concept refers to the parameter list, and not the return type.

In short, rather than invent new names, method overloading can be used when the same form of operation has different implementations. The following method signatures are properly overloaded:

• public int calculator(int);

• public void calculator(double)

• public String calculator(double, int)

• public double calculator(int, double)

Rules Governing Method Overloading.

Usually we overload a method when want to modify any variables in a class, whether by simply resetting their values, or to perform some operations on them. For instance, in the current example, if we wish to change the area of an existing circle, then we could overload the method findArea by passing to it the amount by which we want to modify the radius. This means that we are actually modifying the original value of the variable, radius. Figure 2.15 shows the definition of the overloaded method findArea.

1. public double findArea(float change)

2. {

3. radius = radius + change ;

4. return pi * radius * radius;

5. }

Listing 2.15 The definition of the overloaded method findArea.

Listing 2.16 shows the class definition after the overloaded method findArea is added to it. The order or position in which a member method is placed in a class is not important to the functioning of the class.

1. class areaAndCircumference

2. {

3. private double radius;

4. private static int noOfCircles = 0;

5. private final double pi = 3.14;

6.

7. public areaAndCircumference(double theRadius)

8. {

9. radius = theRadius;

10. }

11. public double findArea()

12. {

13. return pi * radius * radius;

14. }

15.

16. public double findCircumference()

17. {

18. return 2 * pi * radius;

19. }

20.

21. public static int getNumberOfCircles()

22. {

23. return noOfCircles;

24. }

25.

26. public double findArea(float change)

27. {

28. radius = radius + change ;

29. return pi * radius * radius;

30. }

31. }

Listing 2.16 Adding the overloaded method findArea to the class definition.

Listing 2.16 lines 26 – 30 show the inclusion of the overloaded method findArea. Line 26 shows the overloaded method heading. The method heading contains one parameter, that is, the variable change. This variable contains the value that will be used to modify the original value stored in the variable radius. Line 28 shows that by adding the variable change, the value stored in radius is changed. Line 29 simply calculates the area and returns it.

Let us increase the area of circle1 by adding 5 to its radius. In this case the overloaded method findArea is recognized by the parameter list and is called automatically. Listing 2.17 shows the implementation of the overloaded method in Line 7. See Figure 2.15 for the output from the program. The second line of output corresponds to Line 7 of Listing 2.17.

1. class testCircle

2. {

3. public static void main(String[] arg)

4. {

5. areaAndCircumference circle1 =

new areaAndCircumference(10.0);

6. System.out.println("Area of object 1: " +

circle1.findArea() );

7. System.out.println("Area of object 1: " +

circle1.findArea( 5 ) );

8. }

9. }

Listing 2.17 Calling the overloaded method findArea.

[pic]

Figure 2.15 Output from the current run of the program.

Similarly, we could overload the method findCircumference. This will be left as an exercise.

You might be wondering how Java knows which of the methods to call. Very simple, it calls a method by observing the method signatures. That is why for the programmer, it is very important to know the rules governing method overloading.

Default Constructor

A default constructor is a constructor that has no parameter. In this case the value that is assigned to any member variable will be the same each time that an object is created. For instance we could define a default constructor for our class areaAndCircumference. Listings 2.18 and 2.19 are two forms of a default constructor for the class. Both have the same meaning. That is, the variable radius is assigned the value 0.

1. public areaAndCircumference()

2. {

3. radius = 0;

4. }

Listing 2.18 shows a default constructor for the class areaAndCircumference.

The constructor could have been written simply as:

1. public areaAndCircumference()

2. {

3.

4. }

Listing 2.19 An alternate way of writing the above constructor.

If a class is defined without a constructor, then the Java will implicitly supply a default one and will set each instance variable to a default value. Default values will be discussed in when talk about data types are discussed.

Constructor Overloading

Constructors like methods can be overloaded. The rules for overloading constructor are the same as the rules for overloading methods. Listing 2.20 shows a default constructor added to the class areaAndCircumference. However, instead of the initial value 0, let us make it a minimum of one unit. That is, radius = 1.

1. class areaAndCircumference

2. {

3. private double radius;

4. private static int noOfCircles = 0;

5. private final double pi = 3.14;

6.

7. public areaAndCircumference()

8. {

9. radius = 1;

10. noOfCircles = noOfCircles + 1;

11. }

12.

13. public areaAndCircumference(double theRadius)

14. {

15. radius = theRadius;

16. noOfCircles = noOfCircles + 1;

17. }

18.

19. public double findArea()

20. {

21. return pi * radius * radius;

22. }

23.

24. public double findCircumference()

25. {

26. return 2 * pi * radius;

27. }

28.

29. public static int getNumberOfCircles()

30. {

31. return noOfCircles;

32. }

33.

34. public double findArea(float change)

35. {

36. radius = radius + change ;

37. return pi * radius * radius;

38. }

39. }

Listing 2.20 A default constructor added to the class.

Notice that Line 10 updates the variable noOfCircles if this constructor gets called. The implementation of this concept will be left as an exercise.

Rules Governing Constructor.

If a class has more than one constructor, you may be able to use more than one of them to create a single object. This approach avoids you from repeating existing codes. We will explain this concept later in this Part II when we study the implicit reference called this.

Calling Class Method using Reference Variable

Reference variables can be used to call class methods. The format for calling class methods using reference variable is the same as when calling an instance method. See Listing 2.21 Line 13.

1. class testCircle

2. {

3. public static void main(String[] arg)

4. {

5. System.out.println("No of objects: " +

areaAndCircumference.getNumberOfCircles());

6.

7. areaAndCircumference circle1 =

new areaAndCircumference(10.0);

8. System.out.println("No of objects: " +

9. areaAndCircumference.getNumberOfCircles());

10.

11. System.out.println("Area of object 1: " +

circle1.findArea() );

12.

13. System.out.println("Area of object 1: " +

circle1.findArea(5) );

14. System.out.println("No of

objects:"+circle1.getNumberOfCircles());

15. }

16. }

Listing 2.21 Using reference object to call class method.

Figure 2.15 below shows the output from the program. The second to last line of the output was generated by the use of the reference object circle1 to call the class method getNumberOfCircles.

[pic]

Figure 2.15 Output after using reference object to call class method.

Calling Methods From Inside a Class

If two or more methods are members of the same class, you can call any of these methods from within the class by simply using the method name. That is, you do not have to create any object within the class, in order to call a method within the same class. Listing 2.22 Line 3 demonstrates one way of calling the method findCircumference from within the method findArea, and Figure 2.16 shows that when the method findArea is executed the method findCircumference gets executed.

1. public double findArea()

2. {

3. System.out.println("The circumference is: " +

findCircumference());

4. return pi * radius * radius;

5. }

Listing 2.22 Calling a method from within a class.

[pic]

Figure 2.16 The output when the method findCircumference is called from within the method findArea.

How Objects communicate

Objects communicate with each other by passing messages. A message is implemented as a call to:

• A constructor

• A member method of a class, or

• As a value that is returned by a method.

In the first and second cases, values are passed to the called constructor or to the called method via their parameter list. In both cases the constructor heading or the method heading contains at least one parameter.

The term actual parameter refers to values that are passed to the constructor when an object is created or to a method when the method is called. For example, consider Listing 2.21 Line 7, which reads:

areaAndCircumference circle1 = new areaAndCircumference(10.0);

The value 10.0 is the actual parameter value that is passed to the constructor to create the object circle1.

In the case of methods, Listing 2.21 Line 12 shows the actual parameter being passed to the overloaded method findArea. Here is the code.

System.out.println("Area of object 1: " + circle1.findArea(5) );

The value 5 is the actual parameter value that is being passed to the method.

The value of the actual parameter does not necessarily have to be the actual data value as seen in these examples. The actual values could be stored in variables.

The term formal parameter refers to the declaration of variables in the constructor signature and the method signature. Listing 2.20 shows formal parameters on Lines 13 and 34.

Actual and formal parameters must be compatible. That is, the data that is passed from the caller to the constructor or method that is being called, must be in a one-to-one correspondence. Figure 2.17 demonstrates the relationship between both segments. That is, the number of arguments in the parameter list must be the same, the data types must be assignable, and the order in which they are placed must be the same. Assignability of data will be discussed data types.

Figure 2.17 Actual Parameter versus Formal Parameter.

The parameter can either be primitive data types, composite data types, or object.

When a value of a primitive type is passed to a method, if the method changes the value, the value held by the caller will remain unchanged. However, when an object is passed to a method, any change that is made to the object by the method will remain in its changed state when the method is terminated. Hence the caller will observe the change to the object.

In the third case, a non-void method must return a value to the point from which the method was called. The value that is being returned by the method must be type compatible with the type indicated by the return type indicated in the method signature. A non-void method can return a primitive type, a composite type, or an object. Furthermore, a non-void method cannot return more than one value at any time.

Exercises (2j)

1. How are overloaded methods distinguished from each other? Support your answer with three method signatures.

2. Are the following pairs of methods properly overloaded? If not, explain why not.

a) int method(int x, double y){ }

double method(int x, double y){ }

b) int method(int x, double y) { }

void method(double x, int y){ }

c) void method(double x){ }

void method(int x, double y){ }

d) int method(){ }

int method(int x, int y, double z){ }

3. Explain the difference between actual parameter and formal parameter.

4. How is information passed back from a method? Write a method definition to support your answer.

5. The println() method is an example of method overloading. Demonstrate that this is true by providing four uses of this method.

6. What will be printed from the class chain when the class testChain is executed?

public class chain

{

int var;

public chain(double x)

{

this("Hello");

}

public chain(String str)

{

this();

System.out.println(str);

}

public chain()

{

this(200);

System.out.println("years");

}

public chain(int x)

{

System.out.println(x);

}

}

class testChain

{

public static void main(String arg[])

{

chain ch = new chain(100.0);

}

}

7. This exercise refers to Listing 2.20 and Listing 2.21.

a) Type the class areaAndCircumference in Listing 2.20.

b) Type the class testCircle in Listing 2.21.

c) Use the default constructor for class testCircle Listing 2.21, and create a second object.

d) Compile and execute the program.

e) Compare your output with the one below.

[pic]

8. Use the construct in Listing 2.22 to call the method findCircumference from inside the method findArea.

9. Overload the method findCircumference in Listing 2.16.

10. Call the overloaded method findCircumference in Listing 2.17 with the value 5.

Example 2.4.

The ABC Company manufactures office furniture. Prior to manufacturing a product, somethimes the name of the product and the manufacture cost of the product are known. There are situations where the name of the product is known, but the exact cost of the product is not known until after the product has been completed.

Requirement.

A. Based on the problem definition design a class called manufacturing. The class must provide the following:

• Constructor for when the name of a product and the price of the product are known; it must also provide constructor for when only the name of the product is known.

• Instance methods to return the name of the product, to return the price of the product, and a method to change the price of the product.

• A class method that counts the number of manufactured products.

B. Design a class called testManufacturing that creates two products – Chair and Table. The price of the Chair is $40.00, but the price of the Table is not known until after it has been manufactured, when the price is set to $60.00.

Solution

First let us concentrate on the class manufacturing. Let us identify the variables.

• Each product has a name and a price, or name only.

• The class requires two constructors: one that accepts the name and price of the product, the other which accepts only the name of the product.

• Next we identify the actions that are to be performed on each of the variables – return the name, return the price, and change the price. These variables are tied to each of the manufactured product; hence, these variables should be instance variables.

• In addition, we must count the number of products manufactured. This requires a class variable.

Once the variables, the constructors, and the methods have been identified the coding can begin, unless we are not very clear about the algorithm for each method. If the procedure for writing method definition is not clear then you may have to resort to methods such as flowchart, pseudocode, diagrams or charts. In this example the methods are fairly straightforward.

The variables that pertain directly to each product are, the name and the price. Since several products are manufactured, the name and the price of each product are different. Hence these variables aught to be instance variables. Since we must count the number of items manufactured then this necessitates a class variable, as described below.

For instance, there are two constructors: one that accepts a string and a floating point value, the other takes only a string value. See the description below.

The variables name and price are instance variables; hence they require instance methods to access them. That is, to get the name, the price, and to change the price, requires instance methods to access them. The variable count could be accessed by instance method, but because we could ask about the number items produced at anytime, even before the first one is produced, a class method would be more appropriate. See Figure 2.10.

Class name Instance Class Instance Class

Variables Variables Constructor Method Method

manufacturing price count manufacturing1 getName getCount

name manufacturing2 getPrice

changePrice

Once we have carried out this analysis, we can go ahead and write the code for each segment of the discussion. See Listing 2.23 for the complete code for this class.

1. class manufacturing

2. {

3. private String name;

4. private double price;

5. private static int count = 0;

6.

7. public manufacturing(String s)

8. {

9. name = s;

10. price = 0;

11. count = count + 1;

12. }

13.

14. public manufacturing(String s, double p)

15. {

16. name = s;

17. price = p;

18. count = count + 1;

19. }

20.

21. public double getPrice()

22. {

23. return price;

24. }

25.

26. public String getName()

27. {

28. return name;

29. }

30.

31. void changePrice(double p)

32. {

33. price = p;

34. }

35.

36. static int noOfProducts()

37. {

38. return count;

39. }

40. }

Listing 2.23 The class manufacturing.

As stated earlier, this class is a data type. We can compile it, but we cannot execute it. It does not have the method main. We must write a test class containing the method main. From here we create object of manufacturing, and access the methods. Listing 2.24 is the complete code for the test class.

1. public class testManufacturing

2. {

3. public static void main(String[] arg)

4. {

5. System.out.println("The number of items produced is :" +

manufacturing.noOfProducts());

6. manufacturing m1 = new manufacturing("Chair", 40.0);

7. System.out.println("The product is :" + m1.getName());

8. System.out.println("The price of product m1 is: " +

m1.getPrice());

9. System.out.println("The number of items produced is :" +

m1.noOfProducts());

10. manufacturing m2 = new manufacturing("Table");

11. System.out.println("The product is :" + m2.getName());

12. System.out.println("The price of product m2 is: " +

m2.getPrice());

13. System.out.println("The number of items produced is :" +

manufacturing.noOfProducts());

14.

15. m2.changePrice(60.0);

16. System.out.println("The product is :" + m2.getName());

17. System.out.println("The price of product m2 is: " +

m2.getPrice());

18. System.out.println("The number of items produced is :" +

manufacturing.noOfProducts());

19.

20. }

21. }

Listing 2.24 The test class for class manufacturing.

Figure 2.18 shows a possible output from the program.

Figure 2.18 The output from the class manufacturing

The Object Reference, this

When an object is created the compiler generates a variable called this, which refers to the current object. It can be used refer to:

1. Instance variables of the current object.

2. Methods of the current object, and

3. Constructor of the current object.

For instance, a parameter and an instance variable may have the same name. To differentiate between them, we can use the this qualifier to refer to the instance variable of this object. The format for implementing this concept is as follows:

this.identifier = identifier;

Where identifier on the left is the instance variable, and identifier on the right is the parameter variable. This approach is used to avoid the programmer from searching for new names for variables. Listing 2.25 demonstrates its usage.

Suppose we had declared the class areaAndCircumference as follows:

1. AreaAndCircumference

2. {

3. double radius;

4. areaAndCircumference(double radius)

5. {

6. this.radius = radius;

7. }

8. }

Listing 2.25 The variable this is associated with the member variable radius. The variable radius on the right is the parameter.

When this is used to qualify a method, it refers to a method in the current object. This is especially useful when the concept of inheritance comes into play. This is concept beyond the scope of this text. The format for implementing this concept is as follows:

this.methodName();

The variable this can be used to refer to constructor in the current class. This implies that the constructor is overloaded. The format for implementing this concept is as follows:

this()

The intent is to avoid repetition of codes. If a constructor exists and can be used to carry out the initialization process then using the variable this can be used to call a matching constructor within the current class. This concept follows the rules as for passing values from a caller to a constructor or a method. If this construct is used, then the call must be the first statement in the calling constructor. See Listing 2.26, Line 16.

1. class manufacturing

2. {

3. private String name;

4. private double price;

5. private static int count = 0;

6.

7. public manufacturing(String s)

8. {

9. name = s;

10. price = 0;

11. count = count + 1;

12. }

13.

14. public manufacturing(String s, double p)

15. {

16. this( s );

17. price = p;

18. }

19. }

Listing 2.25 Line 16 shows the use of the variable, this, being used to call to the single parameter constructor.

Refer to Listing 2.25 Lines 7 – 19 to see the difference. Notice the following segment of codes:

name = s;

count = count + 1;

Instead of writing the segment of code twice it is written once. The constructor with that segment of code is invoked using this().

Garbage Collection

When objects are created, memory is allocated for each of them. The lifetime of an object is the time from when it was created, to the time when the object can no longer be referenced. If there were no mechanism to reclaim memory resources for objects, when the object can no longer be referenced, then very soon the program would cease to operate due to insufficient memory. The term Garbage Collection means the reclaiming of memory resources from objects whose lifetime have expired, in which case the objects are inactive. Java provides an automatic mechanism of garbage collection through its runtime environment. The automatic garbage collector runs in the background throughout the life of the program. It protects objects that are current, but automatically releases those that are inactive.

For instance, we can declare a reference variable say, circle1and use this variable to create different objects, as seen in the segment of code below.

areaAndCircumference circle1;

circle1 = new areaAndCircumference(10.0);

circle1 = new areaAndCircumference(2.5.0);

circle1 = new areaAndCircumference(15.0);

circle1 = new areaAndCircumference(5.0);

However, each time that we use it to create an object, the reference is removed from the object to which it was referring, and now refers to the newly created object. The former objects are dangling in memory and cannot be referenced anymore. If there was no way to release these blocks of memory, then very soon the machine would run out of memory and the program would halt. It is against this background why Java incorporates this concept of garbage collection in its paradigm. See Figure 2.19.

Reference Variable

Circle1

Figure 2.19 Inactive objects dangling in memory.

Java provides three ways you can to alter the functioning of the automatic garbage collector. You can do this either by:

• Overriding the Java defined collector method finalize(), or

• Invoking the method gc(), to force garbage collection, or

• Invoke the method runFinalizer(), to run the finalizer routines for objects that are eligible for garbage collection.

The Method finalize()

The method finalize is called automatically by Java when an object becomes inactive, but before it is finally destroyed and the space is released. This may take some time after the object has become inaccessibly to the program. However, Java’s virtual machine may not get around to disposing of it immediately. Although Java provides the means of calling this method automatically, you have the option of including it in your program, by overriding the default definition, with your definition. You would override finalize() when an object needs to release resources such as: disk files that were opened for I/O, systems font resources, graphics context resources, or any resources that were provided by the host operating system. You do not have to define it for ordinary things such as variables for primitive data type or composite data types.

The format for defining the method finalize() is as follows:

protected void finalize()

{

// Your code for items that are to be released

}

The method finalize() is an instance method which is defined in the class Object. Therefore, if you need to call this method you will have to create an object of the class in which it is defined, and use this object to call it. For instance, let c1 be an object of some class that contains finalize() Then you would call finalize() this way:

c1.finalize();

The Method gc()

The method finalize() is called only just prior to garbage collection. Therefore, if you need to release resources before finalize() is called, you may do so be calling the method gc(). This method may be called in order to make memory resources from discarded objects available for quick use. The format for calling gc() is as follows:

protected void finalize()

{

System.gc();

}

Or, simply:

System.gc();

If you use the first format, then you would call finalize() as you did in the section above. This call would be for a specific object. The second approach can be used to force garbage collection in general.

The Method runFinalization()

There are times when objects are eligible for garbage collection, but the Java did not run their finalizers before. In a case like this, you can use the method runFinalization() to run the finalizers for those objects. When this method is executed, Java would have made every effort to run all the outstanding finalize methods that have never been run before. The format for calling runFinalization() is as follows:

public static void runFinalization()

{

Runtime.getRuntime().runFinalization();

}

Or simply:

Runtime.getRuntime().runFinalization();

The method runFinalization () is a class method which is defined in the class Runtime().

Suppose runFinalization () was defined in the class areaAndCircumference() then we would call runFinalization () for objects of the class this way:

AreaAndCircumference. runFinalization ()

Summary

In these lessons we covered the fundamental concepts of the type class.

• A class is a user-defined type. It is used to describe an entity.

• A class encapsulates both the data attributes called member variables, and the member methods, into one complete thought.

• Java defines two types of variables: instance variables and class variables. Instance variables cannot be accessed unless an object is created. Class variables can be accessed by class variables; in this case you do not have to create instance of the class.

• The modifier final is used to define a constant.

• Java defines three types of methods: instance method, class method, and constructor.

• Instance methods can only be called if an object is created.

• Class methods can be called without creating instance of the class. This is permissible if no instance variable is involved.

• Instance methods and class methods must have a return type. The modifier void must be used if the method is expected to return no value.

• Constructors are a special member method. They are used to initialize objects, by allocating sufficient memory for the member variables of the class. Constructors do not carry return types, not even the type void. Constructors have the same name as the name of the class.

• All three methods can be overloaded. The parameter list of each overloaded method must be unique. The return type does not play any part in method overloading.

• Modifiers are used to restrict access to data fields and methods. The modifiers are public, protected, and private.

• Objects are created using the new operator. When an object is created it is given its own chunk of memory.

• Java provides an automatic garbage collection mechanism for reclaiming memory from objects that are no longer in use. You can override the automatic garbage collection mechanism.

-----------------------

1. Constructors have the same name as the class itself.

2. Constructors do not have return type, not even the keyword void.

3. The rules for overloading methods are the same for overloading constructors.

1. The number of arguments that are in each method heading must be different, or

2. If the number of arguments is the same in each heading, then at least one of the data type in each heading must be of a different type, or

3. If condition 2 is satisfied, then the order in which the parameters are listed must be arranged differently.

P( dt p, dt q, dt r, …. )

P( x, y, z, …. )

Values For

Actual Parameter

Being Sent

Values For

Formal Parameter

Being Received

radius: 10.0

radius: 5.0

radius: 2.5

radius 15.0

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download