Results 1 to 1 of 1
  1. #1
    Java Exam is offline Member
    Join Date
    Dec 2011
    Posts
    64
    Rep Power
    0

    Default Tutorial:In Depth View of Java Classes for the Java Certification Exam II

    In this article, we will provide an continue our in depth look at Java Classes. In this article we will focus on the initialization of an object from a Java Class, packages, recursion and also extend our discussion of encapsulation. We will also further discuss the benefits derived from these features when developing components in Java,. This is part of a larger series of articles to help you prepare for the java associate exam. To get up to speed on what we have already discussed, see the previous article, “Tutorial:In Depth View of Java Classes for the Java Certification Exam I”.

    Constructors - The Key to Creating Objects from Java Classes

    In order to create an object of a class, a special kind of method called a constructor is invoked. If you don't define any constructors for your class, the compiler will provide a default no-arg constructor in the class that does nothing. The primary purpose of a constructor is to provide you with the means of initializing the instance variables uniquely for the object that is being created. If you are creating a Person object with the name Joe Bloggs, then you want to be able to initialize the member holding the person's name to “Joe Bloggs”. Any initialization blocks that you have defined in a class are always executed before a constructor.

    A constructor has two special characteristics that differentiate it from other class methods:
    • A constructor never returns a value, and you must not specify a return type.
    • A constructor always has the same name as the class.


    Below is the listing for the Sphere class with a constructor:

    Java Code: Sphere class with a constructor
    class Sphere { 
       static final double PI = 3.14; 	// Class variable that has a fixed value
       static int count = 0;		// Class variable to count objects
    
       // Instance variables 
       double radius;			// Radius of a sphere
    
       double xCenter; 			// 3D coordinates
       double yCenter; 			// of the center
       double zCenter;			// of a sphere
        
       // Class constructor 
       Sphere(double theRadius, double x, double y, double z) {
          radius = theRadius;		// Set the radius
    
       // Set the coordinates of the center 
       xCenter = x; 
       yCenter = y; 
       zCenter = z;
       ++count;				// Update object count
    }
    
       // Static method to report the number of objects created 
       static int getCount() {
          return count;			// Return current object count
       }
    
       // Instance method to calculate volume 
       double volume() {
          return 4.0/3.0*PI*radius*radius*radius;
       }
    }
    The constructor has the same name as the class and has no return type specified. A constructor can have any number of parameters, including none. The default constructor has no parameters. In this case the Sphere class constructor has four parameters, and each of the instance variables is initialized with the value of the appropriate parameter. In this listing we have used the name radius for the parameter so we have to use the keyword this to refer to the instance variable of the same name. The last action of the constructor is to increment the class variable count by 1, so that count accumulates the total number of objects created.

    Working with Multiple Constructors

    Constructors are methods that can be overloaded, similar to method overloading in a class that was discussed in the first article on Java Classes, “Tutorial:In Depth View of Java Classes for the Java Certification Exam I”. In most case, you will need to generate objects of a class from different sets of initial defining data. If you just consider the Sphere class which we used as an example in the previous article, you might need to define a Sphere object in a variety of ways. You might well want a constructor that accepted just the (x, y, z) coordinates of a point, and have a Sphere object created with a default radius of 1.0. Another possibility is that you may want to create a default Sphere with a radius of 1.0 positioned at the origin, so no arguments would be specified at all. This requires two constructors in addition to the one we have already written.

    Calling a Constructor within a Constructor

    One class constructor can call another constructor in the same class in its first executable statement. This can often save duplicating a lot of code. To refer to another constructor in the same class, you use this as the method name, followed by the appropriate arguments between parentheses. In the Sphere class, you could have defined the constructors as:

    Java Code: Sphere Class with Multiple Constructors
    class Sphere {
       // Construct a unit sphere at the origin 
       Sphere() {
          radius = 1.0;
          // Other data members will be zero by default
          ++count;			// Update object count
       }
    
       // Construct a unit sphere at a point
       Sphere(double x, double y, double z) {
          this(); 			// Call the constructor with no arguments
          xCenter = x; 
          yCenter = y; 
          zCenter = z;
       }
    
       Sphere(double theRadius, double x, double y, double z) { 
          this(x, y, z);			// Call the 3 argument constructor 
          radius = theRadius;	// Set the radius
       }
    // Rest of the class
    }
    Duplicating Objects with a Constructor

    Sometimes when you need to pass objects to a method, it is necessary to duplicate an object. This type of requirement for object copying occurs quite often in Java. For example if you declare a Sphere object with the following statement:
    Java Code:
    Sphere eightBall = new Sphere(10.0, 10.0, 0.0);
    You can then later in your program create a new object newBall that is identical to the object eightBall by writing the following:

    Java Code:
    Sphere newBall = eightBall;
    Although it might appear to make a copy, it does not. Remember that in this expression the variable newBall is referencing the same object as eightBall. It is not referring to a distinct object. The reason why is that the variable newBall, of type Sphere, is created but no constructor is called, so no new object is created.

    You could also create newBall by specifying the same arguments to the constructor as you used to create eightBall, but it may be that eightBall has been modified in some way such as the position changing during execution of the program, so you don't know that its instance variables have the same values. This presumes that you have some other class methods that alter the instance variables. You could provide the capability for duplicating an existing object by adding a constructor to the class that accepts an existing Sphere object as an argument. This is shown below:

    Java Code: Create a sphere from an existing object
    Sphere(final Sphere oldSphere) {
       radius = oldSphere.radius; 
       xCenter = oldSphere.xCenter; 
       yCenter = oldSphere.yCenter; 
       zCenter = oldSphere.yCenter; 
       ++count;
    }
    The listing shows that what this does is to copy the values of the instance variables of the Sphere object that is passed as the argument to the corresponding instance variables of the new object. Thus the new object that this constructor creates is identical to the Sphere object that is passed as the argument. It is now possible to create newBall as a distinct object by doing the following:

    Java Code: Create a copy of eightBall
    Sphere newBall = new Sphere(eightBall);
    Creating Objects from a Class

    When you declare a variable of type Sphere with the following statement:

    Java Code: Declare a variable
    Sphere ball;
    there is no constructor is called because no object is created. All you have created at this point is the variable ball, which can store a reference to an object of type Sphere, if and when you create one. The figure below shows this:

    Tutorial:In Depth View of Java Classes for the Java Certification Exam II-d7-objectcreation.jpg
    Figure: Object Creation

    As the variable and the object it references are distinct entities, in order to create an object of a class you must use the keyword new followed by a call to a constructor. To initialize ball with a reference to an object, you could write the following:

    Java Code: Create a sphere
    Sphere ball = new Sphere(10.0, 1.0, 1.0, 1.0);
    The listing and the figure shows a Sphere object with a radius of 10.0 located at the coordinates (1.0, 1.0, 1.0). The object is created in memory and occupies a sufficient number of bytes to accommodate all the data necessary to define the object. The variable ball records where in memory the object is it acts as a reference to the object.

    Using Initialization Blocks in a Class

    An initialization block is a block of code between braces that is executed before an object of the class is created. There are two kinds of initialization blocks:
    • A static initialization block is a block defined using the keyword static and is executed once when the class is loaded. A static initialization block can initialize only static data members of the class.
    • A non-static initialization block is executed for each object that is created and thus can initialize instance variables in a class.


    Defining and Using a Class

    To put what you have learned so far about classes to use, you can use the Sphere class in the following example.
    You will create two source files. One file CreateSpheres.java contains the definition of the CreateSpheres class that has the method main() defined as a static method. This is where execution of the program starts. The other file is the Sphere.java file containing the definition of the Sphere class that you have been assembling. The Sphere class definition should look like the following:

    Java Code: Sphere Class Definition
    class Sphere { 
       static final double PI = 3.14;	
       // Class variable that has a fixed value 
       static int count = 0;	// Class variable to count objects
       
       // Instance variables
       double radius;
    
       // Radius of a sphere
       double xCenter; 			// 3D coordinates
       double yCenter; 			// of the center
       double zCenter; 			// of a sphere
      
       // Class constructor 
       Sphere(double theRadius, double x, double y, double z) {
          radius = theRadius;		// Set the radius
          // Set the coordinates of the center 
          xCenter = x; 
          yCenter = y; 
          zCenter = z;
          ++count;				// Update object count
       }
    
       // Static method to report the number of objects created 
       static int getCount() {
          return count;			// Return current object count
       }
    
       // Instance method to calculate volume 
       double volume() {
          return 4.0/3.0*PI*radius*radius*radius;
       }
    }
    Remember that both files need to be in the same directory or folder.

    Example of Creating Classes

    Let’s assume you have been giving an assignment to create a 2D geometry program. Obviously you will need to use more than one class. You will define two classes, a class that represents point objects and a class that represents line objects; you will then use these to find the point at which two lines intersect. We will put the files for the example in a directory or folder with the name Geometry. There is quite of bit of code to write, so we will put it together piecemeal and in order that you understand how each piece works as we go along.

    Creating a Point from Two Lines

    You can add the method to determine the point of intersection between two lines to the Line class. The figure below illustrates how the mathematics works out:

    Tutorial:In Depth View of Java Classes for the Java Certification Exam II-d7-2dgraphicsmath.jpg
    Figure: 2D Graphics Mathematics

    Don’t worry about the mathematics as it is not the most important aspect of the assignment.

    Using Recursion

    The methods you have seen so far have been called from within other methods, but a method can also call itself. A method that calls itself is described as a recursive method, and the process is referred to as recursion. You can also have indirect recursion where a method A calls another method B, which in turn calls the method A. Clearly you must include some logic in a recursive method so that it eventually stops calling itself if the process is not to continue indefinitely.

    You can write a method that calculates integer powers of a variable. So it would evaluate xn, or x*x...*x where x is multiplied by itself n times. You can use the fact that you can obtain xn by multiplying xn—1 by x. So for example, you can calculate 24 as 23 multiplied by 2, and you can get 23 by multiplying 22 by 2, and 22 is produced by multiplying 21 by 2, etc.

    Working with Packages

    Packages are implicit in the organization of the standard classes as well as your own programs, and they influence the names you can use for classes and the variables and methods they contain. Essentially, a package is a uniquely named collection of classes. The primary reason for grouping classes in packages is to avoid possible name clashes with your own classes when you are using prewritten classes in an application. The names used for classes in one package do not interfere with the names of classes in another package or your program because the class names in a package are all qualified by the package name. Thus, the String class you have been using is in the java.lang package, so the full name of the class is java.lang.String. You have been able to use the unqualified name because all the classes in the java.lang package are always available in your program code; there's an implicit import statement in effect for all the names in the java. lang package. If you happened to have defined a class of your own with the name String, using the name String would refer to your class, but you could still use the library class that has the same name by using its full name in your code, java.lang.String.

    All of the standard classes in Java are contained within a set of packages, and each package contains classes that are related in some way. The package that contains most of the standard classes that you have used so far is called java.lang, so called because the classes in this package provide Java language–related support. You haven't seen any explicit reference to java.lang in your code either, because this package is automatically available to your programs. Things are arranged this way because some of the classes in java.lang, such as String, are used in every program. If you use a class from the other packages containing standard classes, you need either to use the fully qualified name of the class or to explicitly import the full class name into your program.

    Packaging Up Your Classes

    Putting one of your classes in a named package is very simple. You just add a package statement as the first statement in the source file containing the class definition. Note that it must always be the first statement. Only comments or blank lines are allowed to precede the package statement. A package statement consists of the keyword package followed by the package name and is terminated by a semicolon. If you want the classes in a package to be accessible outside the package, you must declare the class using the keyword public in the first line of your class definition. Class definitions that aren't preceded by the keyword of public are accessible only from methods in classes that belong to the same package. For example, to include the Line class in a package called Geometry, the contents of the file Line.java needs to be the following:

    Java Code: Example of Line Class
    package Geometry;
    public class Line { 
       // Details of the class definition
    }
    Each class that you want to include in the package Geometry must contain the same package statement at the beginning, and you must save all the files for the classes in the package in a directory with the same name as the package, that is, Geometry. Note the use of the public keyword in the definition of the Line class. This makes the class accessible generally. If you omit the public keyword from the class definition, the class is accessible only from methods in classes that are in the Geometry package.

    Packages and its link to Directory Structure

    Packages are actually a little more complicated because they are intimately related to the directory structure in which it is stored. You already know that the definition of a class with the name ClassName must be stored in a file with the name ClassName.java, and that all the files for classes within a package PackageName must be included in a directory with the name PackageName. You can compile the source for a class within a package and have the .class file that is generated stored in a different directory, but the directory name must still be the same as the package name.

    A package can have a composite name that is a combination of two or more simple names. You can specify a package name as any sequence of names separated by periods. For example, you might have developed several collections of classes dealing with geometry, perhaps one that works with 2D shapes and another with 3D shapes. In this case you might include the class Sphere in a package with the statement

    Java Code:
    package Geometry.Shapes3D;
    and the class for circles in a package using the statement

    Java Code:
    package Geometry.Shapes2D;
    In this situation, the files containing the classes in the Geometry.Shapes3D packages are expected to be in the directory Shapes3D and the files containing the classes in the Geometry.Shapes2D packages are expected to be in the directory Shapes2D. Both of these directories must be subdirectories of a directory with the name Geometry. In general, you can have as many names as you like separated by periods to identify a package, but the package name must reflect the directory structure in which the package is stored.

    Compiling Classes in a Package

    When you compiling the classes in a package you need to assure that the path to the package directory is explicitly made known to the compiler in the value that is set for CLASSPATH, even when the current directory is the one containing the package. The easiest way to specify CLASSPATH is by using the -classpath option when you invoke the compiler. The path to the package directory is the path to the directory that contains the package directory, and therefore does not include the package directory itself.

    For example, if you have stored the source files for classes that are in the Geometry package in the directory with the path C:\MyJavaExamples\Geometry then the path to the Geometry directory is C:\ MyJavaExamples. Many beginners mistakenly specify the path as C:\MyJavaExamples\Geometry, in which case the package is not found.

    You can also tell the compiler about the path to your package by using the –classpath option on the command line. Assuming that the Geometry directory is a subdirectory of C:\ MyJavaExamples, you could compile the Line.java source file with the command:

    Java Code: Compiling of Line.java
    javac -classpath “C:\ MyJavaExamples” Line.java
    If the Point and Line classes were not interrelated, you could still compile the two source files or, indeed, any number of source files, in the Geometry package with the following command:

    Java Code: Compile Command
    javac -classpath “C:\MyJavaExamples” *.java
    Accessing a Package

    How you access a package when you are compiling a program that uses the package depends on where you have put it. There are a couple of options here. The first, but not the best, is to leave the .class files for the classes in the package in the directory with the package name.

    Or with the .class files in the original package directory, either the path to your package must appear in the string that has been set for the CLASSPATH environment variable, or you must use the -classpath option on the command line when you invoke the compiler or the interpreter. This overrides the CLASSPATH environment variable if it happens to be set.

    You need to make sure that the classes in your package are in the right directory. Java does not prevent you from saving a file in a directory that is quite different from that appearing in the package statement. Of the two options here, using the –classpath option on the command line is preferable, because it sets the classpath transiently each time and can't interfere with anything you do subsequently. In any event, you can explore both possibilities.

    Using Extensions to Add Functionality

    Extensions are .jar files stored within the ext directory that is created when you install the JDK. The default directory structure that is created is shown in the figure below:

    Tutorial:In Depth View of Java Classes for the Java Certification Exam II-d7-jdkdirectorystructure.jpg
    Figure: JDK Directory Structure

    The classes and packages in the .jar archives that you place in the ext directory are automatically accessible when you compile or run your Java programs without the need to set the CLASSPATH environment variable or use the –classpath command-line option. When you create a .jar file for a package, you need to make sure that you add the .class files with the directory structure corresponding to the package name—you can't just add the .class files to the archive. For example, suppose you want to store the Geometry package in an archive. Assuming you have already compiled the package and the current directory contains the package directory, you can use the following command to create the archive:

    Java Code: Java Archive Creation
    C:\MyJavaExamples>jar cvf Geometry.jar Geometry\*.class
    This creates the archive Geometry.jar and adds all the .class files that are in the Geometry directory to it. All you now need to do to make the package available to any program that needs it is to copy it to the ext directory in the JDK directory hierarchy shown in Figure 5-9.
    The jar utility does a lot more than I have described here. If you want to know more about what it can do, look into the "Tools and Utilities" section of the JDK documentation.

    Standard Packages in Java

    All of the standard classes that are provided with Java are stored in standard packages. There is a substantial and growing list of standard packages but some of the ones you may hear about most frequently are found in the table below:

    Tutorial:In Depth View of Java Classes for the Java Certification Exam II-d7-standardpackages.jpg
    Table: Standard Packages in Java

    The standard packages and the classes they contain cover an enormous amount of ground, so we will not try and cover them here.

    Standard Classes Encapsulating the Primitive Data Types

    We know from the previous articles in this series that there are classes available that enable you to define objects that encapsulate values of each of the primitive data types in Java. These classes are:

    Tutorial:In Depth View of Java Classes for the Java Certification Exam II-d7-primitivedatatypes.jpg
    Table: Primitive Data Types

    They are part of the package java.lang along with quite a few other classes, such as the String and StringBuffer classes. Each of these classes encapsulates a value of the corresponding primitive type and includes methods for manipulating and interrogating objects of the class, as well as a number of very useful static methods that provide utility functions for the underlying primitive types.

    Conversion between Primitive Type Values and Strings

    Every class provides a static toString() method in order to convert a value of the corresponding primitive type to a String object. There is also a non-static toString() method in each class that returns a String representation of a class object. Conversely, there are methods to convert from a String object to a primitive type. For example, the static parseInt() member in the Integer class accepts a String representation of an integer as an argument and returns the equivalent value as type int.

    An alternative version of this method accepts a second argument of type int that specifies the radix to be used when interpreting the string. This enables you to parse strings that are hexadecimal or octal values, for example. If the String object cannot be parsed for any reason, if it contains invalid characters, for example, the method throws an exception of type NumberFormatException. All the standard classes encapsulating numerical primitive types and the Boolean class define static methods to parse strings and return a value of the corresponding primitive type such as parseShort(), parseByte(), parseInt(), and parseLong().

    Converting Objects to Values

    Each class encapsulating a primitive data value also defines a xxxValue() method (where xxx is the corresponding primitive type name) that returns the value that is encapsulated by an object as a value of the corresponding primitive type. For example, if you have created an object number of type Double that encapsulates the value 1.14159, then the expression number.doubleValue()results in the value 1.14159 as type double.

    Primitive Class Constants

    The classes that wrap numerical primitive types each contain the static final constants MAX_VALUE and MIN_VALUE that define the maximum and minimum values that can be represented. The floating-point classes also define the constants POSITIVE_INFINITY, NEGATIVE_INFINITY, and NaN, so you can use these in comparisons to test whether such values have arisen during calculations. Alternatively, you can test floating-point values with the static methods isInfinite() and isNaN() where you pass your variable as an argument, and the methods return true for an infinite value or the NaN value, respectively. There are also non-static versions for use with an object of the class type. Remember that an infinite value can arise without necessarily dividing by zero. Any computation that results in an exponent that is too large to be represented produces either POSITIVE_INFINITY or NEGATIVE_INFINITY.

    Autoboxing

    There are times where you want to pass values of a primitive type to a method that requires the argument to be a reference to an object. In this case, the compiler supplies automatic conversions of primitive values to the corresponding class type when circumstances permit this. For example, this can arise when you pass a value of type int to a method where the parameter type is type Integer. Conversions from a primitive type to the corresponding class type are called boxing conversions, and automatic conversions of this kind are described as autoboxing.

    Controlling Access to Class Members

    We can refer to any of the static members of the same class in the code for a static class method, and a non-static method can refer to any member of the same class. The degree to which variables and methods within one class are accessible from other classes is a more varied. It depends on what access attributes you have specified for the members of a class, whether the classes are in the same package, and whether you have declared the class as public.

    Using Access Attributes

    Within a given package, any class has direct access to any other class name in the same package for such things as declaring variables or specifying method parameter types, but the variables and methods that are members of that other class are not necessarily accessible. The accessibility of these is controlled by access attributes. The name of a class in one package can be accessed from a class in another package only if the class to be accessed is declared as public. Classes not declared as public can be accessed only by classes within the same package.

    There are four possibilities when specifying an access attribute for a class member, and each possibility has a different effect overall. The options you have for specifying the accessibility of a variable or a method in a class are shown in table below:

    Tutorial:In Depth View of Java Classes for the Java Certification Exam II-d7-accessattributes.jpg
    Table: Access Attributes for a Class Member

    The table shows you how the access attributes you set for a class member determine the parts of the Java environment from which you can access it. Note that public, private, and protected are all keywords. Specifying a member as public makes it completely accessible, and at the other extreme, making it private restricts access to members of the same class. This may sound more complicated than it actually is. The figure below shows the access allowed between classes within the same package:

    Tutorial:In Depth View of Java Classes for the Java Certification Exam II-d7-accesswithinapackage.jpg
    Figure: Access within a Package

    A class definition must have an access attribute of public if it is to be accessible from outside the package that contains it. The figure below shows the situation where the classes seeking access to the members of a public class are in different packages.

    Tutorial:In Depth View of Java Classes for the Java Certification Exam II-d7-accessacrosspackages.jpg
    Figure: Access across Packages

    In the figure above, a package such as packageA only has private members of the class ClassA that can't be directly accessed by methods in other classes in the same package. If you declare a class member to be private, it can be accessed only by methods in the same class. To specify an access attribute for a class member, you just add the appropriate keyword to the beginning of the declaration. Here is the Point class you saw earlier, but now with access attributes defined for its members:

    Java Code: Specifying Access Attributes
    import static java.lang.Math.sqrt;
    public class Point {
       // Create a point from its coordinates
       public Point(double xVal, double yVal) {
          x = xVal; y = yVal;
       }
    
    ...
    }
    Choosing the Appropriate Access Attribute

    The table of access attributes shows that all the classes you have defined so far have had members that are freely accessible within the same package. This applies both to the methods and the variables that were defined in the classes. One of the ideas behind objects is to keep the data members encapsulated so they cannot be modified by all and sundry, even from other classes within the same package. On the other hand, the methods in your classes that provide the operations you want to allow with objects of the class type generally need to be accessible. They provide the outside interface to the class and define the set of operations that are possible with objects of the class. Therefore, you should explicitly specify your class members as either public or private, rather than omitting the access attributes.

    Generally the variables in a public class should be private and the methods that are called from outside the class should be public. Even when access to the values of the variables from outside a class is needed, you don't need to make them public or leave them without an access attribute. You can provide access by simply adding a simple public method to return the value of a data member.

    Using Nested Classes

    All the classes you have defined so far have been separate from each other, each stored in its own source file. Not all classes are defined in this manner. You can put the definition of one class within the definition of another class. The inside class is called a nested class. A nested class can itself have another class nested inside it, if required.

    When you define a nested class, it is a member of the enclosing class in much the same way as the other class members. A nested class can have an access attribute just like other class members, and the accessibility from outside the enclosing class is determined by the attributes in the same way:

    Java Code: Inner Class Example
    public class Outside {
       // Nested class 
       public class Inside {
          // Details of Inside class
          ... 
       }
    
       // More members of Outside class...
    }
    Here the class Inside is nested inside the class Outside. The Inside class is declared as a public member of Outside, so it is accessible from outside Outside. Obviously, a nested class should have some specific association with the enclosing class. It would be non sensical to arbitrarily nest one class inside another. The enclosing class here is referred to as a top-level class. A top-level class is a class that contains a nested class but is not itself a nested class.

    The scope of the nested class is the lifecycle of the outer class. This is because the Inside class is not declared as a static member of the class Outside. Until an object of type Outside has been created, you can't create any Inside objects. However, when you declare an object of a class containing a nested class, no objects of the nested class are necessarily created unless the enclosing class's constructor creates them. For example, if you create an object with the following statement:

    Java Code:
    Outside outer = new Outside();
    No objects of the nested class are created. If you want to create an object of the type of the nested class, you must refer to the nested class type using the name of the enclosing class as a qualifier. For instance, having declared an object of type Outside, you can now create an object of type Inside in the following manner:

    Java Code: Define a nested class object
    Outside.Inside inner = outer.new Inside();
    Here you have created an object of the nested class type that is associated with the object outer that you created earlier. You are creating an object of type Inside in the context of the object outer. Within non- static methods that are members of Outside, you can use the class name Inside without any qualification, as it is automatically qualified by the compiler with the this variable.

    Static Nested Classes

    If you want to make objects of a nested class type independent of objects of the enclosing class type, you can declare the nested class as static:

    Java Code: Static Nested Class
    public class Outside { 
       public static class Skinside {
          // Details of Skinside
       }
    
       // Nested class 
       public class Inside {
          // Details of Inside class
       }
        // More members of Outside class
    }

    Now with Skinside inside Outside declared as static, you can declare objects of this nested class type independent from any objects of type Outside, and regardless of whether you have created any Outside objects or not. Below is an example of using a static nested class:

    Java Code: Static Nested Class Example
    Outside.Skinside example = new Outside.Skinside();
    This is significantly different from what you do for a non-static nested class. Now you must use the nested class name qualified by the enclosing class name as the type for creating the object. Thus, the name of a static nested class exists within the context of the outer class and therefore the nested class name is qualified by the enclosing class name. Note that a static nested class can have static members, whereas a non-static nested class cannot. The figure below illustrates a class containing both a static and a non-static nested class:

    Tutorial:In Depth View of Java Classes for the Java Certification Exam II-d7-nestedclassstaticandnonstatic.jpg
    Figure:Static and Non-static Members with Nested Class

    If the preceding discussion seems a bit confusing in the abstract, you can get a better idea of how a nested class works in practice with a simple example. You create a class MyOuterClass that defines an object containing a variable number of MyInnerClass objects. You put the definition for the class MyInnerClass inside the definition of the class MyOuterClass, so MyInnerClass is an example of a nested class. The basic structure of MyInnerClass.java is:

    Java Code: Example of Nested Class
    public class MyOuterClass { 
       // Definition of the MyOuterClass class...
    
       // Nested class to define a MyInnerClass 
       static class MyInnerClass {
          // Definition of the MyInnerClass class...
       }
    }
    Here the nested class is defined as static because you want to be able to have static members of this class.

    Summary

    In this article, we have reviewed the constructors for classes, access to classes and nested classes. In the next article, we will look at how we can leverage existing classes in our applications.
    Last edited by Java Exam; 05-07-2012 at 09:51 PM.

Similar Threads

  1. Replies: 0
    Last Post: 05-05-2012, 02:36 PM
  2. Replies: 0
    Last Post: 05-03-2012, 12:55 AM
  3. Replies: 0
    Last Post: 05-02-2012, 11:23 AM
  4. Replies: 0
    Last Post: 05-01-2012, 11:10 PM
  5. Replies: 0
    Last Post: 12-12-2011, 01:17 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •