The Artima Developer Community
Sponsored Link

Objects and Java Seminar
Packages and Access Specifiers
Lecture Handout

Agenda


Packages Partition the Name Space


Hierachical Organization


Packages are Libraries


Packages Enable Implementation Hiding


Java Compilation Units


Location of Files


Private Access


Public Access


Package Access


Protected Access


True Meaning of Private and Protected


Exercises

Problem 1.

Select or create a directory of any name on your disk. I will call this directory your working directory. In the working directory, create the following file named Cat.java:

// In file Cat.java
class Cat {

    private Mouse mouse = new Mouse();
}

Then create a subdirectory in the working directory named "hole" and place the following file named Mouse.java in the hole directory:

// In file Mouse.java
package hole;

public class Mouse {
}

At this point, if your working directory happened to be named C:\goodstuff, then you would have two files: C:\goodstuff\Cat.java and C:\goodstuff\hole\Mouse.java.

Finally, change directory to your working directory and compile Cat.java. The compiler should fail with an error message. Your task is to get Cat.java to compile by adding one statement to the Cat.java file. You can't change Mouse.java nor move any any files around.

Problem 2.

In the PackagesAccess/examples/ex1/com/artima/somelib directory of the example source code, edit SplitNameReturnVal.java. Make one small change to this file: change the access level on the class (SplitNameReturnVal) from public to package access.

Change to the PackagesAccess/examples/ex1 directory and attempt to recompile Test.java and Test2.java. These should now fail compilation because SplitNamReturnVal is no longer accessible outside the com.artima.somelib package. Your mission is to move the two test programs to the com.artima.somelib package and get them to compile and run there. This will involve editing the Test*.java files, and moving them to a different directory. Make no other changes to SplitNameReturnVal.java other than changing the access level from public to package.

Problem 3.

Create a Test3 class in the PackagesAccess/examples/ex1 directory, whose main() method invokes Test2's main() method.

Problem 4.

Once you get that Problem 3 working, implement the splitName() method so it actually parses out the title, first, last, and middle names. Create a test program named Test3 that accepts one to four command line arguments. It concatenates these one to four command line arguments, separating each by a space character, into a string that is passed to splitName(). Print out the name after it has been split.


Sponsored Links

Copyright © 1996-2014 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us