Special java subject - Part 2

public class AClass { public int instanceInteger = 0; public int instanceMethod() { return instanceInteger; } public static int classInteger = 0; public static int classMethod() { return classInteger; } public static void main(String[] args) { AClass anInstance = new AClass(); AClass anotherInstance = new AClass();

ppt58 trang | Chia sẻ: tlsuongmuoi | Lượt xem: 1876 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Special java subject - Part 2, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
CLASSES AND OBJECT SPECIAL JAVA SUBJECT The Elements of a class Declaring Classes Declaring Member Variables Defining Methods Defining Methods Access level: public, protected, private Default is package private Controlling Access to Members of a Class Understanding Instance and Class Members public class AClass { public int instanceInteger = 0; public int instanceMethod() { return instanceInteger; } public static int classInteger = 0; public static int classMethod() { return classInteger; } public static void main(String[] args) { AClass anInstance = new AClass(); AClass anotherInstance = new AClass(); Understanding Instance and Class Members //Refer to instance members through an instance. anInstance.instanceInteger = 1; anotherInstance.instanceInteger = 2; System.out.println("Instance method 1: " + anInstance.instanceMethod()); System.out.println("Instance method 2: " + anotherInstance.instanceMethod()); //Illegal to refer directly to instance members from a class method //System.out.println("Instance method 1: " + instanceMethod()); //System.out.println("Instance method 2: " + instanceInteger); Understanding Instance and Class Members //Refer to class members through the class... AClass.classInteger = 7; System.out.println("Class method: " +classMethod()); //...or through an instance. (Possible but not generally recommended.) System.out.println("Class method from an Instance:" + anInstance.classMethod()); //Instances share class variables anInstance.classInteger = 9; System.out.println("Class method from an Instance1:" + anInstance.classMethod()); System.out.println("Class method from an Instance2:" + anotherInstance.classMethod()); } } Initializing Instance and Class Members Using Static Initialization Blocks import java.util.*; class Errors { static ResourceBundle errorStrings; static { try { errorStrings = ResourceBundle.getBundle("ErrorStrings"); } catch (MissingResourceException e) { //error recovery code here } } } Initializing Instance and Class Members Using Static Initialization Blocks import java.util.*; class Errors { static ResourceBundle errorStrings = initErrorStrings(); private static ResourceBundle initErrorStrings() { try { return ResourceBundle.getBundle("ErrorStrings"); } catch (MissingResourceException e) { //error recovery code here } } } Exercise public class StringAnalyzer2 { private String origin; private String delimiter; public StringAnalyzer2(String origin, String delimiter){ . . . . . . } public boolean hasMoreElement(){ . . . . . . } public String getNextElement(){ . . . . . . } } OBJECT BASICS Creating Objects Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne,100,200); Rectangle rectTwo = new Rectangle(50, 100); Each statement has the following three parts: Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. Instantiation: The new keyword is a Java operator that creates the object. As discussed below, this is also known as instantiating a class. Initialization: The new operator is followed by a call to a constructor. For example, Point(23, 94) is a call to Point's only constructor. The constructor initializes the new object. Declaring a Variable to Refer to an Object type name This notifies the compiler that you will use name to refer to data whose type is type. The Java programming language divides variable types into two main categories: primitive types, and reference types. The declared type matches the class of the object: MyClass myObject = new MyClass(); or MyClass myObject; The declared type is a parent class of the object's class: MyParent myObject = new MyClass(); or MyParent myObject The declared type is an interface which the object's class implements: MyInterface myObject = new MyClass(); or MyInterface myObject A variable in this state, which currently references no object, is said to hold a null reference. Initializing an Object public class Point { public int x = 0; public int y = 0; public Point(int x, int y) { this.x = x; this.y = y; } } Point originOne = new Point(23, 94); public class Rectangle { public int width; public int height; public Point origin; public Rectangle(Point p, int w, int h) { origin = p; width = w; height = h; } } Rectangle rectOne = new Rectangle(originOne, 100, 200); Initializing an Object Using Objects You can use an object in one of two ways: Directly manipulate or inspect its variables Call its methods Referencing an Object's Variables The following is known as a qualified name: objectReference.variableName System.out.println("Width of rectOne: " + rectOne.width); System.out.println("Height of rectOne: " + rectOne.height); int height = new Rectangle().height; Calling an Object's Methods objectReference.methodName(); or objectReference.methodName(argumentList); System.out.println("Area of rectOne: " + rectOne.area()); rectTwo.move(40, 72); Passing Object Reference Variables When you pass an object variable into a method, you must keep in mind that you're passing the object reference, and not the actual object itself. Remember that a reference variable holds bits that represent (to the underlying VM) a way to get to a specific object in memory (on the heap). import java.awt.Dimension; class ReferenceTest { public static void main (String [] args) { Dimension d = new Dimension(5,10); ReferenceTest rt = new ReferenceTest(); System.out.println("Before modify() d.height = "+ d.height); rt.modify(d); System.out.println("After modify() d.height = "+ d.height); } void modify(Dimension dim) { dim.height = dim.height + 1; System.out.println("dim = " + dim.height); } } Passing Object Reference Variables Before modify() d.height = 10 dim = 11 After modify() d.height = 11 Passing Object Reference Variables public class PassingVar extends TestCase{ public void modify(Student st){ st.setName("Tran Thi B"); st = new Student("Le Van C"); } public void test() { Student sv1 = new Student("Nguyen Van A"); System.out.println("Before modify():"+sv1); modify(sv1); System.out.println("After modify():"+sv1); } } Before modify():Nguyen Van A After modify():Tran Thi B Passing Primitive Variables public class SwapNumber extends TestCase{ public void swap(int a, int b){ int c = a; a = b; b = c; } public void test(){ int a = 1, b = 2; System.out.println("Before swap a: "+ a + " , b: "+b); swap(a,b); System.out.println("After swap a: "+ a + " , b: "+b); } } Passing Primitive Variables public class SwapNumber extends TestCase{ public void swap(Integer a1, Integer b1){ Integer c = a1; a1 = b1; b1 = c; } public void test(){ Integer a = new Integer (1), b = new Integer (2); System.out.println("Before swap a: "+ a + " , b: "+b); swap(a,b); System.out.println("After swap a: "+ a + " , b: "+b); } } Cleaning Up Unused Objects The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection. An object is eligible for garbage collection when there are no more references to that object. The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right. Cleaning Up: Nulling a Reference The first way to remove a reference to an object is to set the reference variable that refers to the object to null. public class GarbageTruck { public static void main(String [] args) { StringBuffer sb = new StringBuffer("hello"); System.out.println(sb); // The StringBuffer object is not eligible for collection sb = null; // Now the StringBuffer object is eligible for collection } } Cleaning Up: Reassigning a Reference Variable class GarbageTruck { public static void main(String [] args) { StringBuffer s1 = new StringBuffer("hello"); StringBuffer s2 = new StringBuffer("goodbye"); System.out.println(s1); // At this point the StringBuffer "hello" is not eligible s1 = s2; // Redirects s1 to refer to the "goodbye" object // Now the StringBuffer "hello" is eligible for collection } } import java.util.Date; public class GarbageFactory { public static Date getDate() { Date d2 = new Date(); StringBuffer now = new StringBuffer(d2.toString()); System.out.println(now); return d2; } public static void main(String [] args) { Date d = getDate(); doComplicatedStuff(); System.out.println("d = " + d) ; } } Cleaning Up:Reassigning a Reference Variable Cleaning Up: Isolating a Reference Cleaning Up: Forcing Garbage Collection import java.util.Date; public class CheckGC { public static void main(String [] args) { Runtime rt = Runtime.getRuntime(); System.out.println("Total JVM memory: " + rt.totalMemory()); System.out.println("Before Memory = " + rt.freeMemory()); Date d = null; for(int i = 0; i= 0; i--) { dest.append(palindrome.charAt(i)); } System.out.format("%s%n", dest.toString()); } } In addition to length, the StringBuffer and StringBuilder classes have a method called capacity, which returns the amount of space allocated rather than the amount of space used. Getting Characters by Index public char charAt(int index) Returns the char value in this sequence at the specified index. The first char value is at index 0. public String substring(int start) Returns a substring begins at the specified index and extends to the end of this sequence. public String substring(int start, int end) Returns a substring begins at the specified start and extends to the character at index end - 1. Getting Characters by Index String anotherPalindrome = "Niagara. O roar again!"; char aChar = anotherPalindrome.charAt(9); String roar = anotherPalindrome.substring(11, 15); Searching for a Character or a Substring within a String (String class) The StringBuffer and StringBuilder classes do not support the indexOf or the lastIndexOf methods. If you need to use these methods on either one of these objects, first convert to a string by using the toString method public class FilenameDemo { public static void main(String[] args) { final String FPATH = "/home/mem/index.html"; Filename myHomePage = new Filename(FPATH,'/', '.'); System.out.println("Extension = " + myHomePage.extension()); System.out.println("Filename = " + myHomePage.filename()); System.out.println("Path = " + myHomePage.path()); } } FilenameDemo Extension = html Filename = index Path = /home/mem FileName public class Filename { private String fullPath; private char pathSeparator, extensionSeparator; public Filename(String str, char sep, char ext) { fullPath = str; pathSeparator = sep; extensionSeparator = ext; } public String extension() { int dot = fullPath.lastIndexOf(extensionSeparator); return fullPath.substring(dot + 1); } FileName public String filename() { int dot = fullPath.lastIndexOf(extensionSeparator); int sep = fullPath.lastIndexOf(pathSeparator); return fullPath.substring(sep + 1, dot); } public String path() { int sep = fullPath.lastIndexOf(pathSeparator); return fullPath.substring(0, sep); } } Comparing Strings and Portions of Strings Comparing Strings and Portions of Strings RegionMatchesDemo public class RegionMatchesDemo { public static void main(String[] args) { String searchMe = "Green Eggs and Ham"; String findMe = "Eggs"; int len = findMe.length(); boolean foundIt = false; int i = 0; while (!searchMe.regionMatches(i, findMe, 0, len)) { i++; foundIt = true; } if (foundIt) { System.out.println(searchMe.substring(i, i+len)); } } } Modifying String Buffers and String Builders Modifying String Buffers and String Builders

Các file đính kèm theo tài liệu này:

  • pptSPECIAL JAVA SUBJECT part 2.ppt
Tài liệu liên quan