![]() C# uses contravariance in its generic type type parameters. Contravariance - In contravariance a typing rule must preserve the order of types such that a type can be replaced by itself or a supertype.Java covariance type rules for both method overriding and array types. Covariance - In covariance a typing rule must preserve the order of types such that a type can be replaced by itself of a subtype.In Java, A1 must be equal to A2 or a subtype thereof, this also applies to B2.What is the rule called contravariance? Give an example of a language that uses the contravariant rule.What is the rule called covariance? Give an example of a language that uses the covariant rule.Investigate and report on this aspect of inheritance, citing the sources you used. Different languages have very different rules about how the types A1 and A2, and B1 and B2, must be related. Suppose a derived class C2 defines a method m of type A2->B2 that overrides a method m of type A1->B1, inherited from the base class C1. I2 can be downcast to a C2 which is-a I1 via inheritance from C1 I1 can be cast to a C1 which can be downcast to a C2 Think carefully about why.) Check Your Learning: Solution: Assignment ( Hint: An assignment of c1 to i2 is allowed with a downcast, even though the class C1 clearly does not implement interface I2. Suppose two reference variables x and y have the declared types R and S like this:įor each possible assignment of one of these five variables to another, say whether Java allows it, disallows it, or allows it only with a downcast, and explain why. Public class FormattedInteger In Class Exercises Exercise 1 It checks the string to make sure it has the appropriate format and returns an error message if there is any problem. The setString method is the only slightly complicated one. (All three of these examples are string representations for the same number.) The class uses an enumeration to encode which of the three formats it will understand. The class handles three different string representations: ordinary signed decimal integers, such as “-2” hex integers starting with “0x”, such as “0xfffffffe” and octal integers starting with “0”, such as “037777777776”. It also has the methods getString and setString, which allow a client to get and set the stored value using a string representation. ![]() It has the methods getInt and setInt to get and set the stored value. However, since our code will only allow us to set values in the array using set(), which will enforce that only objects of type Ecan be added, then such a typecast cannot fail. The following Java class, FormattedInteger, stores a single integer value. Assuming that we did not have getArray()as a method, technically, we are performing an unchecked downcast at REF 1.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |