[ Pobierz całość w formacie PDF ] .Analogous to converting a primitive value to a larger type, some objects may not need to be castexplicitly.In particular, because instances subclasses usually contain all the information thatinstances superclasses do, you can use an instance of a subclass anywhere a superclass is expected.Suppose you have a method that takes two arguments: one of type Object, and one of typeNumber.You don t have to pass instances of those particular classes to that method.For the Objectargument, you can pass any subclass of Object (any object, in other words), and for the Numberargument you can pass in any instance of any subclass of Number (Integer, Boolean, Float, andso on).Casting an object to an instance of one of that object s superclasses loses the information theoriginal subclass provided and requires a specific cast.To cast an object to another class, you usethe same casting operation that you used for base types:(classname) objectIn this case, classname is the name of the class you want to cast the object to, and object is areference to the object you re casting.Note that casting creates a new instance of the new classwith all the information that the old object contained; the old object still continues to exist asit did before.Here s a (fictitious) example of a cast of an instance of the class GreenApple to an instance of theclass Apple (where GreenApple is theoretically a subclass of Apple):GreenApple a;Apple a2;72SSFRWTMDAYDAYWorking with Objects4Comparing ObjectsYesterday, you learned about operators for comparing values: equals, not equals, less than, andso on.Most of these operators work only on primitive types, not on objects.If you try to use othervalues as operands, the Java compiler produces errors.The exception to this rule is with the operators for equality: == (equal) and != (not equal).Theseoperators, when used with objects, tests whether the two operands refer to exactly the sameobject.What should you do if you want to be able to compare instances of your class and havemeaningful results? You have to implement special methods in your class, and you have to callthose methods using those method names.Technical Note: Java does not have the concept of operator overloading that is,the capability of defining the behavior of the built-in operators by defining meth-ods in your own classes.The built-in operators remain defined only for numbers.A good example of this is the String class.It is possible to have two strings, two independentobjects in memory with the same values that is, the same characters in the same order.According to the == operator, however, those two String objects will not be equal, because,although their contents are the same, they are not the same object.The String class, therefore, defines a method called equals() that tests each character in thestring and returns true if the two strings have the same values.Listing 4.4 illustrates this.TypeListing 4.4.A Test of String Equality.1: class EqualsTest {2:3: public static void main (String args[]) {4: String str1, str2;5: str1 = she sells sea shells by the sea shore. ;6: str2 = str1;7:8: System.out.println( String1: + str1);9: System.out.println( String2: + str2);10: System.out.println( Same object? + (str1 == str2));11:12: str2 = new String(str1);13:14: System.out.println( String1: + str1);15: System.out.println( String2: + str2);16: System.out.println( Same object? + (str1 == str2));17: System.out.println( Same value? + str1.equals(str2));18: }19: }74SSFRWTMabcdString1: she sells sea shells by the sea shore.String2: she sells sea shells by the sea shore.OutputSame object? trueString1: she sells sea shells by the sea shore.String2: she sells sea shells by the sea shore.Same object? falseSame value? trueThe first part of this program (lines 4 through 6) declares two variables, str1 and str2,Analysisassigns the literal she sells sea shells by the sea shore.to str1, and then assigns thatvalue to str2.As you know from object references, now str1 and str2 point to the sameobject, and the test at line 10 proves that.In the second part, you create a new string object with the value of str1.Now you have twodifferent string objects with the same value.Testing them to see whether they re the same objectby using the == operator (line 16) returns the expected answer, as does testing them using theequals method (line 17) to compare their values.Technical Note: Why can t you just use another literal when you change str2,rather than using new? String literals are optimized in Java if you create a string4using a literal, and then use another literal with the same characters, Java knowsenough merely to give you the first String object back.Both strings are the sameobjects to create two separate objects you have to go out of your way.Copying ObjectsRecall from the section on object references that assigning variables and passing objects asarguments to methods affect only the object s reference and doesn t create copies of thoseobjects.How do you create copies of objects? There are two ways: the copy() method and theclone() method.The copy() method (defined in Object, and so available to all objects), takes a single argumentanother instance of the same class and copies the values of all the argument s instance variablesinto the instance variables of the current object (the one in which you re calling the method).Note that if those instance variables in turn hold references to objects, only the references arecopied, not the objects.Point pt1, pt2, pt3;pt1 = new Point(0,0);pt2 = new Point(100,100);pt2.copy(pt1); // pt1 s values are copied into pt2; both now are (0,0).75LearningSams.netCenterDAYDAYWorking with Objects4The clone() method is similar to copy(), except that clone() takes no arguments.The clone()method creates a new instance of the same class as the source object and then copies the valuesof the instance variables (either primitive types or references to other objects).clone() returnsan instance of the class Object; to use it as an instance of the original class you have to cast it.Here s an example that clones the Point object in pt2 and stores the result in pt3:pt3 = (Point) pt2.clone();Determining the Class of an ObjectWant to find out the class of an object? Here s the way to do it for an object assigned to thevariable obj:String name = obj.getClass().getName();What does this do? The getClass() method is defined in the Object class, and as such is availablefor all objects.The result of that method is a Class object (where Class is itself a class), whichhas a method called getName().getName() returns a string representing the name of the class.Another test that might be useful to you is the instanceof operator.instanceof has twooperands: an object on the left, and the name of a class on the right.The expression returns trueor false based on whether the object is an instance of the named class or any of that class ssuperclasses: foo instanceof String // truePoint pt = new Point(10,10);pt instanceof String // falseThe instanceof operator can also be used for interfaces; if an object implements an interface,the instanceof operator with an interface name on the right side returns true.You ll learn allabout interfaces in Week 3.The Java Class LibrariesTo finish up today, let s look at the some of the Java class libraries.Actually, you ve had someexperience with them already, so they shouldn t seem that strange
[ Pobierz całość w formacie PDF ]
zanotowane.pldoc.pisz.plpdf.pisz.plhanula1950.keep.pl
|