Creating and Using Classes

Team-Fly

Now that you have created an object, you need to define the template for it. Templates for objects are called classes, and they include variables, methods, and hierarchy.

Defining a Class

A simple class can be defined with the Java keyword class as shown here:

class TestClass {     // Class components go here }

The convention normally used for a class is to capitalize the first letter. The components that are in a class are typically called members of that class and come in the two broad categories of variables and methods. By default, all classes become public classes. Therefore, the class can be used by other classes in the class hierarchy. You can also declare two other types of classes. The first is an abstract class that cannot be instantiated to an object but is meant to contain other classes (subclasses). To declare an abstract class, use the keyword abstract before the keyword class in the declaration, as shown next.

abstract class HighLevel {     // Class Members }

The other type of class is called final. Declaring a class as final means that no other class can be subclassed to it. Thus, by definition, a final class is the lowest class in the class hierarchy.

final class LowestLevel {     // Class Members }

Declaring Member Variables

As you may recall from Chapter 6, two types of variables can be included in a class: instance variables and class variables. Instance variables are copied each time a new object for a class is created; class variables are not copied, but are global to all objects that are instantiated from the class. You define instance variables within the class definition, as shown in the following example:

class Test1 {     int x;     boolean flag; }

Any object that is created from this class will have its own variables of x and flag. Class variables are defined by putting the keyword static before the declaration of the variable.

 class Test2 {     int x;     boolean flag;     static int total; }

Here, each object that is created from class Test2 will have its own variables (x and flag) and will share the variable total with all other objects created from the class Test2.

If you want to declare a variable with a constant value in a class, use the keyword final before the data declaration. This keyword indicates that the value of the variable will not change.

class Test3 {     int x;     boolean flag;     static int total;     final  int maxobject = 10; }

Later, in the section 'Controlling Access to Members of a Class,' you will see how to further control access to variables of a class, using access specifiers like Private and Protected.

Methods

Methods are simply pieces of code that perform a specific task. In other programming languages, methods are called subroutines, forms, or functions. The simple form of a method declaration is as follows:

class Test4 {     static total;     method addOne()     {         ++total;     } }

In this example any object created from Test4 can use the addOne method to increment the class variable total.

Test4 obj1 = new Test4(); obj1.addOne();

If you are familiar with other programming languages, the concept of methods may seem rather routine so far. However, Java does depart from many other languages in that the name of the method is not enough to uniquely define it among other members. Java also looks at the types of the arguments that are declared with the method. You can, therefore, declare two methods with the same name within one class as long as each method has a different set of arguments associated with it.

Note 

The concept of using the name of the method along with its arguments to uniquely define the method is called method overloading.

To indicate that a method will be expecting arguments, you declare the arguments in the definition of the method.

exampleMethod(int arg1, float arg2 . . .);

If you declare arguments in the definition of the method, they are valid only within that method. If the name of an argument variable is the same as that of a variable declared in the class, the class variable is hidden by the local argument variable. The following example demonstrates this concept.

public class Test5 {     int x = 2;     void method1()     {         System.out.println("Method1 X = " + x);     }     void method2(int x)     {        ++x;         System.out.println("Method2 X = " + x);     }     public static void main (String[] args)     {         Test5 obj1 = new Test5();         obj1.method1();         obj1.method2(2);         obj1.method1();     } }

When executed, the example produces the following output:

Method1 X = 2;    // The initial value of instance variable X Method1 X = 3;    // The value of the local variable x Method1 X = 2;    // The instance variable has not changed value

If you need to access a class variable in a method where both the class variable and the argument for the method have the same name, you can use Java's 'this' operator. When you use 'this,' you are referring to the object itself and hence are accessing the instance variables of the object. You can also call other methods from that object with Java's 'this' operator. The following full code example demonstrates 'this':

public class Test6 {     int x = 1;     void method1(int x)     {         this.x = x;         ++x;         System.out.println("Local X = " + x);         this.printx();     }     void printx()     {         System.out.println("Instance X = " + x);     }    public static void main (String[] args)     {         Test6 obj1 = new Test6();         obj1.method1(5);     } }

The results from the example are as follows:

Local X = 6; Instance X = 5;

It is important to understand how Java passes variables into methods. In Java, variables are passed by value, and you are not allowed to change these values in the method. Therefore, if you pass in primitive data arguments, they cannot be changed, and if you pass in objects (which are really references to an object), you cannot change the object. However, you are allowed to call methods of the object to change values within the object.

The default return value for a method is void or no return at all. If your method is going to return some value, you must define what type it will be when you declare the method. The next example again uses the addOne method, but this time addOne returns the total after incrementing it.

class Test7 {     static int total;     int addOne()     {         ++total;         return total;     } }

You can declare instance methods and class methods, just as you can with variables. Class methods differ from instance methods in that you do not need to have an object instantiated from the class before you use the method. The declaration of a class method is just like that of variables, through the keyword static. This keyword is used to define many methods in Java's core classes like Math.abs().

Constructor Methods

A constructor method is called when a new instance of the class is created. Java performs this step automatically; constructor methods cannot be called directly. You usually use constructor methods to initialize variables for new objects. Constructor methods are not required when you create a class.

You create a constructor method just like any other method except that a constructor method will have the same name as the class and cannot have any return value (constructor methods are typed as a void). You can also overload constructor methods so that you can call up different pieces of code based on the types of the arguments passed in.

class Test8 {     int x;     Test8(int y)     {         x = y;     }     Test8()     {         x = 1;     } }

In the preceding example, a new instance of the class Test6 can be created with either of the following lines of code:

Test8 obj1 = new Test8();  // obj1.x = 1; Test8 obj1 = new Test8(3); // obj1.x = 3;

There is one more type of method to discuss: the finalize method. However, to fully understand how the finalize method works, you need to understand a little more about class hierarchy and access control. The finalize method is covered in the 'Finalizer Methods' section later in the chapter.

Subclasses, Superclasses, and Inheritance

Chapter 6 introduced the concept of class hierarchy. Basically, a class hierarchy allows you to define a high-level class with variables and methods that are common to many other classes; you can then nest these other classes under the high-level class, and they will all have access to the high-level class' members. A hierarchy can have any number of levels.

In Java the lower-level class is referred to as a subclass, and the upper-level class is referred to as the superclass. Members that are defined in the superclass but are used in the subclasses are referred to as inherited members.

A class hierarchy is created by creating the superclass first and then creating the subclass as an extension of the superclass, as shown next.

class test9 {     int x; } class test10 extends Test9 {     int y; }

If an object is instantiated with class test10, the object will have both the x and y variables.

As with instance and method argument variables, if a variable is named the same in both the superclass and subclass, the subclass member is used as a local member. If you want to access the variable in the superclass, you can use the Java operator super, as shown in the following example:

class Test11 {     int x = 2; } class Test12 extends Test11 {     int  x = 3;    void printsuperx()     {         System.out.println("Super X = " + super.x);     } }

If an object is instantiated from class Test12, a call to the printsuperx method will return 'Super X = 2,' even though the value of x in the subclass is 3.

In the case of methods, if you have methods with the same name and argument list in both the superclass and subclass, the subclass method is called instead of the superclass method. This process of using the local method instead of the one in the superclass is referred to as method overriding. If you want to access the superclass method instead of the subclass method, you can use the Java operator super as described in the preceding example with variables.

Controlling Access to Members of a Class

One advantage of object-oriented programming is that an object should be able to control access to members such as variables and methods. Java breaks access control into four distinct levels: private, protected, public, and package. Each level can be assigned to all declarations including classes, variables, and methods.

One key point about access levels is that they do more than just protect information from being seen. Access levels can prevent other classes from modifying variables that are critical or that should be modified only by routines within a class or group of classes.

Private Access

Private access is the most restrictive form of access that you can use. Members with Private access can be accessed only by that class or by objects initiated from it. The following code example declares Private access and states what is legal and what is not.

public class Test13 {     public static void main (String[] args)     {        Test14 obj1 = new Test14();         obj1.setx();       // You can set X this way         obj1.printx();     // You can print X this way         obj1.x = 3;        // Syntax error since x is private         obj1.secretx();    // Syntax error since secretx is private         obj1.setsecret()   // Ok since setsecret is not private     } } public class Test14 {     private int x;     void setx()     {         x = 2;     }     void printx()     {         System.out.println("In Test14, X=" + x);     }     private void secretx()     {         x = 3;     }     void setsecret()     {         this.secretx();     } }

Protected Access

The next level of access is Protected access. Protected access is a bit less restrictive than Private access. Protected access allows the class, subclasses, and all classes that are in the same package to access the member. Packages are discussed later in this chapter, but for now you can think of a package as a collection of classes.

Public Access

If a member is defined as public, then all classes have access to it. Therefore, any other class can set and display variables or execute methods that are declared this way.

Package Access

Package access is the default access level that is assigned to a member if no other access level is declared. Package access means that any other class of the same package has full access to a member defined with this type of access.

Finalizer Methods

Now that we have finished discussing access control and how to define hierarchy among classes, we can discuss the finalizer methods. Finalizer methods are called just before an object is destroyed during a garbage collection. Remember that Java automatically and periodically performs garbage collection on objects that no longer have a valid reference in the system. Finalizer methods are generally used to clean up references in other objects that are affected by this object. An example might be a class variable that keeps track of the number of objects instantiated with this class; in this case the finalizer method could be used to decrement the class variable just before an object is destroyed.


Team-Fly


Java & BAPI Technology for SAP
Java & BAPI Technology for SAP
ISBN: 761523057
EAN: N/A
Year: 1998
Pages: 199

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net