500 likes | 638 Views
JAVA Programcılığı 3.1.2. Ali R+ SARAL. Ders Planı 3.1.2. Understanding Packages Controlling Access to Class Members Nested Classes The finalize() Method Native Methods. Packaging Up Your Classes. A package is a uniquely named collection of classes.
E N D
JAVA Programcılığı 3.1.2 Ali R+ SARAL
Ders Planı 3.1.2 • Understanding Packages • Controlling Access to Class Members • Nested Classes • The finalize() Method • Native Methods
Packaging Up Your Classes • A package is a uniquely named collection of classes. • The primary reason is to avoid possible name clashes with your own classes • when you are using prewritten classes in an application.
Packaging Up Your Classes • To include the Sphere class in a package called Geometry, • the contents of the file Sphere.java would need to be: package Geometry; public class Sphere { // Details of the class definition }
Packages and the Directory Structure • package Geometry.Shapes3D; • and the class for circles in a package using the statement: • 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.
Accessing a Package • set CLASSPATH=.;C:\MySource;C:\MyPackages
Adding Classes from a Package to Your Program • import Geometry.Shapes3D.*; // Include all classes from this package • import Geometry.Shapes3D.Sphere; // Include the class Sphere • Note that the * can be used only to select all the classes in a package. • You can’t use Geometry.* to select all the packages in the Geometry directory.
Packages and Names in Your Programs • Geometry.Shapes3D.Sphere ball = new Geometry.Shapes3D.Sphere(10.0, 1.0, 1.0, 1.0);
Importing Static Class Members double volume() { return 4.0/3.0*Math.PI*radius*radius*radius; } import static java.lang.Math.PI; class Sphere { // Class details as before... double volume() { return 4.0/3.0*PI*radius*radius*radius; } } import static java.lang.Math.*; // Import all static members of the Math class
Standard Packages • javax.swing Provides classes supporting the “Swing” GUI components. These are not only more flexible and easier to use than the java.awt equivalents, but they are also implemented largely in Java with minimal dependency on native code. • javax.swing.border Classes to support generating borders around Swing components • javax.swing.event Classes supporting event handling for Swing components. • java.awt.event Contains classes that support event handling. • java.awt.geom Contains classes for drawing and operating with 2D geometric entities • java.applet Contains classes that enable you to write applets—programs that are • embedded in a web page. • java.util Contains classes that support a range of standard operations for • managing collections of data, accessing date and time information, and analyzing strings.
Standard Packages • java.langContains classes that are fundamental to Java (e.g., the Math class) • and all of these are available in your programs automatically. You do not need an import statement to include them. • java.ioContains classes supporting stream input/output operations. • java.nio Contains classes supporting the new input/output operations that were introduced in JDK1.4—especially with files. • java.nio.channelsContains more classes supporting new input/output operations— the ones that actually read and write files. • java.awtContains classes that support Java’s graphical user interface (GUI). While you can use these classes for GUI programming, it is almost always easier and better to use the alternative Swing classes. • javax.swingProvides classes supporting the “Swing” GUI components. These are not only more flexible and easier to use than the java.awt equivalents, but they are also implemented largely in Java with minimal dependency on native code. • javax.swing.borderClasses to support generating borders around Swing components • javax.swing.eventClasses supporting event handling for Swing components. • java.awt.eventContains classes that support event handling. • java.awt.geomContains classes for drawing and operating with 2D geometric entities • java.appletContains classes that enable you to write applets—programs that are embedded in a web page. • java.utilContains classes that support a range of standard operations for managing collections of data
Standard Classes Encapsulating the Primitive Data Types • Boolean Character Byte • Short Integer Long • Float Double
Autoboxing Values of Primitive Types • To pass values of a primitive type to a method that requires the argument to be a reference to an object. • The compiler will supply automatic conversions of primitive values to the corresponding class type when circumstances permit this.
Try It Out Autoboxing in Action (missing) public class AutoboxingInAction { public static void main(String[] args) { int[] values = { 3, 97, 55, 22, 12345 }; Integer[] objs = new Integer[values.length]; // Array to store Integer objects // Call method to cause boxing conversions for(int i = 0 ; i<values.length ; i++) { objs[i] = boxInteger(values[i]); } // Use method to cause unboxing conversions for(Integer intObject : objs) { unboxInteger(intObject); } } // Method to cause boxing conversion public static Integer boxInteger(Integer obj) { return obj; } // Method to cause unboxing conversion public static void unboxInteger(int n) { System.out.println(“value = “ + n); } }
Controlling Access to Class Members • how you control the accessibility of class members from outside the class—from a method in another class in other words.
Using Access Attributes • 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.
Using Access Attributes • Attribute Permitted Access • No access attributeFrom methods in any class in the same package • publicFrom methods in any class anywhere as long as the class has been declared as public • privateAccessible only from methods inside the class. No access from outside the class at all. • protectedFrom methods in any class in the same package and from any subclass anywhere
Try It Out Accessing the Point Class 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; } // Create a Point from an existing Point object public Point(final Point aPoint) { x = aPoint.x; y = aPoint.y; } // Move a point public void move(double xDelta, double yDelta) { // Parameter values are increments to the current coordinates x += xDelta; y += yDelta; }
Try It Out Accessing the Point Class // Calculate the distance to another point public double distance(final Point aPoint) { return sqrt((x – aPoint.x)*(x – aPoint.x)+(y – aPoint.y)*(y – aPoint.y)); } // Convert a point to a string public String toString() { return Double.toString(x) + “, “ + y; // As “x, y” } // Coordinates of the point private double x; private double y; }
Using Package and Access Attributes How do I create a .JAR file? • Java Archive (JAR) files allow developers to package many classes into a single file. JAR files also use compression, so this can make applets and applications smaller. • Creating a .JAR file is easy. Simple go to the directory your classes are stored in and type :- • jar -cf myfile.jar *.class If your application or applet uses packages, then you'll need to do things a little differently. Suppose your classes were in the package mycode.games.CoolGame - you'd change to the directory above mycode and type the following :- (Remember to use / on UNIX systems) • jar -cf myfile.jar .\mycode\games\CoolGame\*.class Now, if you have an existing JAR file, and want to extract it, you'd type the following • jar -xf myfile.jar
Try It Out Packaging Up the Line and Point Classes package Geometry; 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; } // Create a Point from an existing Point object public Point(final Point aPoint) { x = aPoint.x; y = aPoint.y; }
Try It Out Packaging Up the Line and Point Classes // Move a point public void move(double xDelta, double yDelta) { // Parameter values are increments to the current coordinates x += xDelta; y += yDelta; } // Calculate the distance to another point public double distance(final Point aPoint) { return sqrt((x – aPoint.x)*(x – aPoint.x)+(y – aPoint.y)*(y – aPoint.y)); } // Convert a point to a string public String toString() { return Double.toString(x) + “, “ + y; // As “x, y” }
Try It Out Packaging Up the Line and Point Classes // Retrieve the x coordinate public double getX() { return x; } // Retrieve the y coordinate public double getY() { return y; } // Set the x coordinate public void setX(double inputX) { x = inputX; } // Set the y coordinate public void setY(double inputY) { y = inputY; } // Coordinates of the point private double x; private double y; }
Try It Out Packaging Up the Line and Point Classes package Geometry; public class Line { // Create a line from two points public Line(final Point start, final Point end) { this.start = new Point(start); this.end = new Point(end); } // Create a line from two coordinate pairs public Line(double xStart, double yStart, double xEnd, double yEnd) { start = new Point(xStart, yStart); // Create the start point end = new Point(xEnd, yEnd); // Create the end point } // Calculate the length of a line public double length() { return start.distance(end); // Use the method from the Point class }
Try It Out Packaging Up the Line and Point Classes // Return a point as the intersection of two lines -- called from a Line object public Point intersects(final Line line1) { Point localPoint = new Point(0, 0); double num =(this.end.getY() – this.start.getY()) * (this.start.getX()– line1.start.getX()) - (this.end.getX() – this.start.getX()) * (this.start.getY() – line1.start.getY()); double denom = (this.end.getY() – this.start.getY()) * (line1.end.getX() – line1.start.getX()) - (this.end.getX() – this.start.getX()) * (line1.end.getY() – line1.start.getY()); localPoint.setX(line1.start.getX() + (line1.end.getX() – line1.start.getX())*num/denom); localPoint.setY(line1.start.getY() + (line1.end.getY() – line1.start.getY())*num/denom); return localPoint; }
Try It Out Packaging Up the Line and Point Classes // Convert a line to a string public String toString() { return “(“ + start+ “):(“ + end + “)”; // As “(start):(end)” } // that is, “(x1, y1):(x2, y2)” // Data members Point start; // Start point of line Point end; // End point of line }
Try It Out Testing the Geometry Package import Geometry.*; // Import the Point and Line classes public class TryPackage { public static void main(String[] args) { double[][] coords = { {1.0, 0.0}, {6.0, 0.0}, {6.0, 10.0}, {10.0,10.0}, {10.0, -14.0}, {8.0, -14.0}}; // Create an array of points and fill it with Point objects Point[] points = new Point[coords.length]; for(int i = 0; i < coords.length; i++) points[i] = new Point(coords[i][0],coords[i][1]); // Create an array of lines and fill it using Point pairs Line[] lines = new Line[points.length – 1]; double totalLength = 0.0; // Store total line length here for(int i = 0; i < points.length – 1; i++) { lines[i] = new Line(points[i], points[i+1]); // Create a Line totalLength += lines[i].length(); // Add its length System.out.println(“Line “+(i+1)+’ ‘ +lines[i] + “ Length is “ + lines[i].length()); } // Output the total length System.out.println(“\nTotal line length = “ + totalLength); } }
Nested Classes public class Outside { // Nested class public class Inside { // Details of Inside class... } // More members of Outside class... }
Nested Classes • Outside outer = new Outside(); • Outside.Inside inner = outer.new Inside(); // Define a nested class object • Inside inner = new Inside(); // Define a nested class object • this.Inside inner = this.new Inside(); // Define a nested class object
Static Nested Classes public class Outside { public static class Skinside { // Details of Skinside } // Nested class public class Inside { // Details of Inside class... } // More members of Outside class... } Outside.Skinside example = new Outside.Skinside();
Static Nested Classes public class MagicHat { // Definition of the MagicHat class... // Nested class to define a rabbit static class Rabbit { // Definition of the Rabbit class... } }
Try It Out Rabbits out of Hats import java.util.Random; // Import Random class public class MagicHat { static int maxRabbits = 5; // Maximum rabbits in a hat static Random select = new Random(); // Random number generator // Constructor for a hat public MagicHat(String hatName) { this.hatName = hatName; // Store the hat name rabbits = new Rabbit[1+select.nextInt(maxRabbits)]; // Random rabbits for(int i = 0; i < rabbits.length; i++) { rabbits[i] = new Rabbit(); // Create the rabbits } }
Try It Out Rabbits out of Hats // String representation of a hat public String toString() { // Hat name first... String hatString = “\n” + hatName + “ contains:\n”; for(Rabbit rabbit : rabbits) { hatString += “ “ + rabbit; // Add the rabbits strings } return hatString; } private String hatName; // Name of the hat private Rabbit rabbits[]; // Rabbits in the hat // Nested class to define a rabbit static class Rabbit { // Definition of the Rabbit class... } }
Try It Out Rabbits out of Hats public class MagicHat { // Definition of the MagicHat class – as before... // Nested class to define a rabbit static class Rabbit { // A name is a rabbit name from rabbitNames followed by an integer static private String[] rabbitNames = {“Floppsy”, “Moppsy”, “Gnasher”, “Thumper”}; static private int[] rabbitNamesCount = new int[rabbitNames.length]; private String name; // Name of the rabbit // Constructor for a rabbit public Rabbit() { int index = select.nextInt(rabbitNames.length); // Get random name index name = rabbitNames[index] + (++rabbitNamesCount[index]); } // String representation of a rabbit public String toString() { return name; } } }
Try It Out Rabbits out of Hats public class TryNestedClass { static public void main(String[] args) { // Create three magic hats and output them System.out.println(new MagicHat(“Gray Topper”)); System.out.println(new MagicHat(“Black Topper”)); System.out.println(new MagicHat(“Baseball Cap”)); } }
Using a Non-Static Nested Class • You saw earlier that • a non-static nested class cannot have static members, so you must find an alternative way of • Dealing with names if you want to make Rabbit a non-static nested class. • The answer is to keep rabbitNames and rabbitNamesCount as static, • but put them in the MagicHat class instead. Let’s see that working.
Try It Out Accessing the Top-Level Class Members public class MagicHat { static int maxRabbits = 5; // Maximuum rabbits in a hat static Random select = new Random(); // Random number generator static private String[] rabbitNames = {“Floppsy”, Moppsy”,“Gnasher”, “Thumper”}; static private int[] rabbitNamesCount = new int[rabbitNames.length]; // Constructor for a hat public MagicHat(final String hatName) { this.hatName = hatName; // Store the hat name rabbits = new Rabbit[1+select.nextInt(maxRabbits)]; // Random rabbits for(int i = 0; i < rabbits.length; i++) { rabbits[i] = new Rabbit(); // Create the rabbits } }
Try It Out Accessing the Top-Level Class Members // String representation of a hat public String toString() { // Hat name first... String hatString = “\n” + hatName + “ contains:\n”; for(Rabbit rabbit : rabbits) { hatString += “ “ + rabbit; // Add the rabbits strings } return hatString; } private String hatName; // Name of the hat private Rabbit rabbits[]; // Rabbits in the hat // Nested class to define a rabbit class Rabbit { private String name; // Name of the rabbit
Try It Out Accessing the Top-Level Class Members // Constructor for a rabbit public Rabbit() { int index = select.nextInt(rabbitNames.length); // Get random name index name = rabbitNames[index] + (++rabbitNamesCount[index]); } // String representation of a rabbit public String toString() { return name; } } }
Using a Nested Class Outside the Top-Level Class • You can create objects of an inner class outside the top-level class containing the inner class. • System.out.println(“An independent rabbit: “ + new MagicHat.Rabbit()); • This Rabbit object is completely free—there is no MagicHat object to contain and restrain it. In the case of a non-static Rabbit class, things are different.
Try It Out Free-Range Rabbits (Almost) static public void main(String[] args) { // Create three magic hats and output them System.out.println(new MagicHat(“Gray Topper”)); System.out.println(new MagicHat(“Black Topper”)); System.out.println(new MagicHat(“Baseball Cap”)); MagicHat oldHat = new MagicHat(“Old hat”); // New hat object MagicHat.Rabbit rabbit = oldHat.new Rabbit(); // Create rabbit object System.out.println(oldHat); // Show the hat System.out.println(“\nNew rabbit is: “ + rabbit); // Display the rabbit }
Local Nested Classes • You can define a class inside a method—where it is called a local nested class. It is also referred to as a • local inner class, since a non-static nested class is often referred to as an inner class. You can create • objects of a local inner class only locally—that is, within the method in which the class definition • appears.
The finalize() Method • This method is called automatically by Java before an object is finally destroyed and the space it occupies in memory is released. • protected void finalize() { • // Your clean-up code... • } • You can suggest to the JVM that the • finalize() methods for all discarded objects should be run, if they haven’t been already. • call the runFinalization() method: • System.runFinalization();
Native Methods • public native long getData(); // Declare a method that is not in Java • Of course, the method will have no body in Java since it is defined elsewhere, • where all the work is done, so the declaration ends with a semicolon. • The implementation of a native method will need to use an interface to the Java environment. • The standard API for implementing native methods in C, for example, is called JNI—the Java Native Interface. • The major drawback to using native methods in Java is that your program will no longer be portable.