Upcoming SlideShare
×

# Chapter 4:Object-Oriented Basic Concepts

418 views

Published on

Exam Objective 1.1 Describe, compare, and contrast primitives (integer, floating point,boolean, and character), enumeration types, and objects.
Exam Objective 3.1 Develop code that uses primitives, enumeration types, and object references, and recognize literals of these types.

Published in: Technology
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

### Chapter 4:Object-Oriented Basic Concepts

1. 1. Object-Oriented Basic Concepts 1
2. 2. • Exam Objective 1.1 Describe, compare, and contrast primitives (integer, floating point,boolean, and character), enumeration types, and objects. • Exam Objective 3.1 Develop code that uses primitives, enumeration types, and object references, and recognize literals of these types. 2
3. 3. Primitive Data Types All numeric primitive types are signed. Ben Abdallah Helmi Architect en 3 J2EE
4. 4. 1. A signed data type has an equal number of non-zero positive and negative values available. A. True B. False Ben Abdallah Helmi Architect en 4 J2EE
5. 5. 1. B. The range of negative numbers is greater by one than the range of positive numbers. Ben Abdallah Helmi Architect en 5 J2EE
6. 6. 9. What is the range of values that can be assigned to a variable of type short? A. Depends on the underlying hardware B. 0 through 216 − 1 C. 0 through 232 − 1 D. −215 through 215 − 1 E. −231 through 231 − 1 Ben Abdallah Helmi Architect en 6 J2EE
7. 7. 9. D. The range for a 16-bit short is −215 through 215 − 1. This range is part of the Java specification,regardless of the underlying hardware. Ben Abdallah Helmi Architect en 7 J2EE
8. 8. 10. What is the range of values that can be assigned to a variable of type byte? A. Depends on the underlying hardware B. 0 through 28 − 1 C. 0 through 216 − 1 D. −27 through 27 − 1 E. −215 through 215 − 1 Ben Abdallah Helmi Architect en 8 J2EE
9. 9. 10. D. The range for an 8-bit byte is −27 through 27 −1. Table 1.3 lists the ranges for Java’s integral primitive data types. Ben Abdallah Helmi Architect en 9 J2EE
10. 10. Literals • Literals can represent primitive or string variables and may appear on the right side of assignments or in method calls. • The only valid literals of boolean type are true and false. For example: • 1. boolean isBig = true; • 2. boolean isLittle = false; • A chararacter literal (char) represents a single Unicode character. char c = ’w’; • Of course, this technique works only if the desired character is available on the keyboard at hand.Another way to express a char literal is as a Unicode value specified using four hexadecimal digits, preceded by u, with the entire expression in single quotes. For example: • Char c1 = ’u4567’; • ’n’ for new line • ’r’ for return • ’t’ for tab • ’b’ for backspace • ’f’ for formfeed • ’’’ for single quote • ’” ’ for double quote • ’’ for backslash Ben Abdallah Helmi Architect en 10 J2EE
11. 11. • Integral literals may be assigned to any numeric primitive data type. They may be expressed in decimal, octal, or hexadecimal. The default is decimal. To indicate octal, prefix the literal with 0 (zero). To indicate hexadecimal, prefix the literal with 0x or 0X; the hex digits may be upper- or lowercase. The value 28 may thus be expressed six ways: • 28 • 034 • 0x1c • 0x1C • 0X1c • 0X1C • By default, an integral literal is a 32-bit value. To indicate a long (64-bit) literal, append the suffix L to the literal expression. (The suffix can be lowercase, but then it looks so much like a one that your readers are bound to be confused.) • The letter E or e, indicating scientific notation, such as 4.23E+21 • The suffix F or f, indicating a float literal, such as 1.828f • The suffix D or d, indicating a double literal, such as 1234d A floating-point literal with no F or D suffix defaults to double type. Ben Abdallah Helmi Architect en 11 J2EE
12. 12. String Literals • A string literal is a sequence of characters enclosed in double quotes. For example: • String s = “Characters in strings are 16-bit Unicode.”; Ben Abdallah Helmi Architect en 12 J2EE
13. 13. 2. Choose the valid identifiers from those listed here. (Choose all that apply.) A.BigOlLongStringWithMeaninglessName B. \$int C. bytes D. \$1 E. finalist Ben Abdallah Helmi Architect en 13 J2EE
14. 14. 2. A, B, C, D, E. All of the identifiers are valid. An identifier begins with a letter, a dollar sign, or an underscore; subsequent characters may be letters, dollar signs, underscores, or digits. And ofcourse keywords and their kin may not be identifiers. Ben Abdallah Helmi Architect en 14 J2EE
15. 15. 16. Which of the following are legal? (Choose all that apply.) A. int a = abcd; B. int b = ABCD; C. int c = 0xabcd; D. int d = 0XABCD; E. int e = 0abcd; F. int f = 0ABCD; Ben Abdallah Helmi Architect en 15 J2EE
16. 16. 16. C, D. The characters a–f and A–F may be combined with the digits 0–9 to create a hexadecimal literal, which must begin with 0x. Ben Abdallah Helmi Architect en 16 J2EE
17. 17. 17. Which of the following are legal? (Choose all that apply.) A. double d = 1.2d; B. double d = 1.2D; C. double d = 1.2d5; D. double d = 1.2D5; Ben Abdallah Helmi Architect en 17 J2EE
18. 18. 17. A, B. The d suffix in option A and the D suffix in option B are optional. Options C and D are illegal because the notation requires e or E, not d or D. Ben Abdallah Helmi Architect en 18 J2EE
19. 19. 18. Which of the following are legal? A. char c = 0x1234; B. char c = u1234; C. char c = ‘u1234’; Ben Abdallah Helmi Architect en 19 J2EE
20. 20. 18. C. A Unicode literal character must be enclosed in single quotes and must begin with u. Ben Abdallah Helmi Architect en 20 J2EE
21. 21. Arrays • A Java array is an ordered collection of primitives, object references, or other arrays. • A method that takes an array of doubles could be declared as myMethod(double dubs[]) or as myMethod(double[] dubs); • a method that returns an array of doubles may be declared as either double[] anotherMethod() or as double anotherMethod()[]. • When an array is constructed, its elements are automatically initialized to their default values. Ben Abdallah Helmi Architect en 21 J2EE
22. 22. int[][] myInts = { {1, 2, 3}, {91, 92, 93, 94}, {2001, 2002} }; When you realize that the outermost array is a single-dimension array containing references, you understand that you can replace any of the references with a reference to a different subordinate array, provided the new subordinate array is of the right type. For example, you can do the following: int[][] myInts = { {1, 2, 3}, {91, 92, 93, 94}, {2001, 2002} }; int[] replacement = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; myInts[1] = replacement; Ben Abdallah Helmi Architect en 22 J2EE
23. 23. Ben Abdallah Helmi Architect en 23 J2EE
24. 24. Variables and Initialization Member variable A member variable of a class is created when an instance is created, and it is destroyed when the object is destroyed. Subject to accessibility rules and the need for a reference to the object, member variables are accessible as long as the enclosing object exists. Automatic variable An automatic variable of a method is created on entry to the method and exists only during execution of the method, and therefore it is accessible only during the execution of that method. (You’ll see an exception to this rule when you look at inner classes, but don’t worry about that for now.) Class variable A class variable (also known as a static variable) is created when the class is loaded and is destroyed when the class is unloaded. There is only one copy of a class variable, and it exists regardless of the number of instances of the class, even if the class is never instantiated. Static variables are initialized at class load time Ben Abdallah Helmi Architect en 24 J2EE
25. 25. All member variables that are not explicitly assigned a value upon declaration are automatically assigned an initial value. The initialization value for member variables depends on the member variable’s type. A member value may be initialized in its own declaration line: 1. class HasVariables { 2. int x = 20; 3. static int y = 30; When this technique is used, nonstatic instance variables are initialized just before the class constructor is executed; here x would be set to 20 just before invocation of any HasVariables constructor. Static variables are initialized at class load time; here y would be set to 30 when the HasVariables class is loaded. Ben Abdallah Helmi Architect en 25 J2EE
26. 26. Automatic variables (also known as method local variables are not initialized by the system; every automatic variable must be explicitly initialized before being used. For example, this method will not compile: 1. public int wrong() { 2. int i; 3. return i+5; 4. } The compiler error at line 3 is, “Variable i may not have been initialized.” This error often appears when initialization of an automatic variable occurs at a lower level of curly braces than the use of that variable. For example, the following method returns the fourth root of a positive number: 1. public double fourthRoot(double d) { 2. double result; 3. if (d >= 0) { 4. result = Math.sqrt(Math.sqrt(d)); 5. } 6. return result; 7. } Here the result is initialized on line 4, but the initialization takes place within the curly braces of lines 3 and 5. The compiler will flag line 6, complaining that “Variable result may not have been initialized.” A common solution is to initialize result to some reasonable default as soon as it is declared: 1. public double fourthRoot(double d) { 2. double result = 0.0; // Initialize 3. if (d >= 0) { 4. result = Math.sqrt(Math.sqrt(d)); 5. } 6. return result; 7. } Ben Abdallah Helmi Architect en 26 J2EE
27. 27. 5. Consider the following line of code: int[] x = new int[25]; After execution, which statements are true? (Choose all that apply.) A. x[24] is 0 B. x[24] is undefined C. x[25] is 0 D. x[0] is null E. x.length is 25 Ben Abdallah Helmi Architect en 27 J2EE
28. 28. 5. A, E. The array has 25 elements, indexed from 0 through 24. All elements are initialized to 0. Ben Abdallah Helmi Architect en 28 J2EE
29. 29. Argument Passing: By Reference or by Value 1. public void bumper(int bumpMe) { 2. bumpMe += 15; 3. } Line 2 modifies a copy of the parameter passed by the caller. For example 1. int xx = 12345; 2. bumper(xx); 3. System.out.println(“Now xx is “ + xx); line 3 will report that xx is still 12345. Ben Abdallah Helmi Architect en 29 J2EE
30. 30. When Java code appears to store objects in variables or pass objects into method calls, the object references are stored or 1. Button btn; passed. 2. btn = new Button(“Pink“); 3. replacer(btn); 4. System.out.println(btn.getLabel()); 5. 6. public void replacer(Button replaceMe) { 7. replaceMe = new Button(“Blue“); 8. } Line 2 constructs a button and stores a reference to that button in btn. In line 3, a copy of the reference is passed into the replacer() method. the string printed out is “Pink”. Ben Abdallah Helmi Architect en 30 J2EE
31. 31. 1. Button btn; 2. btn = new Button(“Pink“); 3. changer(btn); 4. System.out.println(btn.getLabel()); 5. 6. public void changer(Button changeMe) { 7. changeMe.setLabel(“Blue“); 8. } the value printed out by line 4 is “Blue”. Ben Abdallah Helmi Architect en 31 J2EE
32. 32. Arrays are objects, meaning that programs deal with references to arrays, not with arrays themselves. What gets passed into a method is a copy of a reference to an array. It is therefore possible for a called method to modify the contents of a caller’s array. Ben Abdallah Helmi Architect en 32 J2EE
33. 33. 6.Consider the following application: class Q6 { public static void main(String args[]) { Holder h = new Holder(); h.held = 100; h.bump(h); System.out.println(h.held); } } class Holder { public int held; public void bump(Holder theHolder) { theHolder.held++; } } } What value is printed out at line 6? A. 0 B. 1 C. 100 D. 101 Ben Abdallah Helmi Architect en 33 J2EE
34. 34. 6. D. A holder is constructed on line 3. A reference to that holder is passed into method bump() on line 5. Within the method call, the holder’s held variable is bumped from 100 to 101. Ben Abdallah Helmi Architect en 34 J2EE
35. 35. 7. Consider the following application: 1. class Q7 { 2. public static void main(String args[]) { 3. double d = 12.3; 4. Decrementer dec = new Decrementer(); 5. dec.decrement(d); 6. System.out.println(d); 7. } 8. } 9. 10. class Decrementer { 11. public void decrement(double decMe) { 12. decMe = decMe - 1.0; 13. } 14. } Review Questions 31 What value is printed out at line 6? A. 0.0 B. 1.0 C. 12.3 D. 11.3 Ben Abdallah Helmi Architect en 35 J2EE
36. 36. 7. C. The decrement() method is passed a copy of the argument d; the copy gets decremented, but the original is untouched. Ben Abdallah Helmi Architect en 36 J2EE
37. 37. 20. Which of the following are true? (Choose all that apply.) A. Primitives are passed by reference. B. Primitives are passed by value. C. References are passed by reference. D. References are passed by value. Ben Abdallah Helmi Architect en 37 J2EE
38. 38. 20. B, D. In Java, all arguments are passed by value. Ben Abdallah Helmi Architect en 38 J2EE
39. 39. The Object Class The Object class is the ultimate ancestor of all Java classes. If a class does not contain the extends keyword in its declaration, the compiler builds a class that extends directly from Object if (d1 == d2) The comparison will be true if the reference in d1is equal to the reference in d2 . Of course, this is the case only when both variables refer to the same object. public boolean equals(Object object) Ben Abdallah Helmi Architect 39
40. 40. The Object class provides a clone() method, which returns a copy of the current object. In other words, the clone has the same class as the original, and all its data values are identical. Thus all references in the clone point to the same objects as those pointed to in the original.Object’s version of clone() is protected, so a class’ clone() may not be called by any code anywhere. If you want a class’ clone() to be public, you need to insert something like the following: public Object clone() throws CloneNotSupportedException { return super.clone(); } Notice the CloneNotSupportedException. It is not a runtime exception, so it must be dealt with. Classes that override clone() generally declare that they implement java.lang.Cloneable, which defines the single clone() Ben Abdallah Helmi Architect method. 40
41. 41. 13. Which of the following are legal clone() methods in a class called Q13 that extends Object? • A. public Object clone() { return super.clone(); } • B. public Object clone() throws CloneNotSupportedException { return super.clone(); } • C. public Q13 clone() { return (Q13)super.clone(); } • D. public Q13 clone() throws CloneNotSupportedException { return (Q13)super.clone(); } Ben Abdallah Helmi Architect 41
42. 42. 13. B, D. The CloneNotSupportedException must be dealt with, so A and C are wrong. The version being overridden (in Object) has return type Object, so prior to release 5.0 the return type in D would be illegal; however, now that covariant returns are legal, D is allowed. Ben Abdallah Helmi Architect 42
43. 43. Enums • 5.0 introduces the enum, which is a class with certain added functionality and also certain restrictions. • Enums are subclasses of java.lang.Enum. Ben Abdallah Helmi Architect 43 43 J2EE
44. 44. public class TrafficLight { private int state; // 1 means red // 2 means yellow // 3 means green public int getState() { return state; } } Assume that the class also contains timing code to change the state at appropriate intervals. Ben Abdallah Helmi Architect 44 44 J2EE
45. 45. This class is extremely prone to error. Anyone who modifies the class or calls getState() has to know that 1 means red, 2 means yellow, and 3 means green. If anyone’s code gets confused even for a moment about which value means which color, the resulting bug could be very difficult to track down. The common solution is to introduce constants: public class TrafficLight { public final static int RED = 1; public final static int YELLOW = 2; public final static int GREEN = 3; private int state; public int getState() { return state; } } Ben Abdallah Helmi Architect 45 45 J2EE
46. 46. This code compares the light’s state only to constants defined in the TrafficLight class, never to literal integer values. You can hope people who call getState() use this approach; you can insist they do so in daily e-mail memos; but you can’t guarantee they will do so. Our code so far has numerous drawbacks, especially these: It is possible to assign an out-of-range value to a light’s state. Printing a light’s state is not very informative. Ben Abdallah Helmi Architect 46 46 J2EE
47. 47. A more robust approach is shown here: 1. public class LightState { 2. protected final String name; 3. 4. public final static LightState RED = new LightState("red"); 5. public final static LightState YELLOW = new LightState("yellow"); 6. public final static LightState GREEN = new LightState("green"); 7. 8. private LightState(String s) { 9. name = s; 10. } 11. 12. public String name() { 13. return name; 14. } 15. } The new approach represents states by using instances of the LightState class, rather than ints. Note that the constructor is private, so you can never construct any instances from outside the class or its subclasses; the only instances you will ever need are constructed statically. Ben Abdallah Helmi Architect 47 47 J2EE
48. 48. You can’t use the new class as a switch statement argument as you could with the ints of the previous example, but that’s a small price to pay. Our original switching code becomes LightState state = nextTrafficLight.getState(); if (state == LightState.RED) stop(); else if (state == LightState.YELLOW) floorIt(); else if (state == LightState.GREEN) proceed(); else assert false : “null light state.”; Ben Abdallah Helmi Architect 48 48 J2EE
49. 49. • This design ensures that the only possibly unexpected state value for a traffic light is null. • Also, debugging code can print out any LightState instance and produce an informative result. In fact, this approach is so useful that it has a name: the typesafe enumeration design pattern. It is considered typesafe because there is a dedicated type whose sole purpose is to encode a few enumerated states, thus avoiding the dangers of using arbitrarily assigned int values. Ben Abdallah Helmi Architect 49 49 J2EE
50. 50. • • • • public class A extends Enum { } // erreur public class A extends Option { } // erreur public enum Option extends A { } // erreur public enum Option extends Option { } // erreur Ben Abdallah Helmi Architect 50 50 J2EE
51. 51. public enum Age { jeune(20), mure(40), agé(60), vieux(80), cadavérique(999); Age(int année) { this.année=année; } private final int année; private static Age getAge(int année) { for(Age age:Age.values()) if (age.année>=année) return age; return cadavérique; } public static void main(String[] args) { System.out.println(getAge( new Scanner(System.in).nextInt())); } // 35 mure Ben Abdallah Helmi Architect 51 51 J2EE
52. 52. public enum Option { l{ public void performs() { System.out.println("long"); } }, a { public void performs() { System.out.println("all"); } }, v { public void performs() { System.out.println("verbose"); } }; public abstract void performs(); public static void performs(Set<Option> set) { for(Option option:set) option.performs(); } } Ben Abdallah Helmi Architect 52 52 J2EE
53. 53. public interface Performer { public void performs(); } public enum Option implements Performer { l{ public void performs() { System.out.println("long"); } }, a{ public void performs() { System.out.println("all"); } }; } Ben Abdallah Helmi Architect 53 53 J2EE
54. 54. • You can declare an enum anywhere you can declare a class. • Compiling an enum generates a .class file whose name is derived from the enum’s name. • Enums inherit data and methods from Object. • Enums may be converted and cast according to the same rules that govern any class that extends Object. • Enums may have main() methods and can be invoked as applications. • Enums that have no explicit constructors get default no-args constructors. • Enums have restricted functionality. They are unlike traditional classes in the following ways: • Enums are declared with the enum keyword rather than the class keyword. • Enums may not be instantiated. • Enums may not extend anything and may not be extended. • Enums may be arguments in switch statements. • Enums have built-in name() and toString() methods, both of which return the name of the current instance. Ben Abdallah Helmi Architect 54 J2EE 54
55. 55. switch (nextTrafficLight.getState()) { case LightState.RED: stop(); break; case LightState.YELLOW: floorIt(); break; case LightState.GREEN: proceed(); break; default: assert false: “null light state”; public enum LightState { } RED, YELLOW, GREEN; } Ben Abdallah Helmi Architect 55 55 J2EE
56. 56. enum Quark { UP('u', 2.0/3.0), DOWN('d', -1.0/3.0), CHARM('c', 2.0/3.0), STRANGE('s', -1.0/3.0), TRUTH('t', 2.0/3.0), BEAUTY('b', -1.0/3.0); private final char symbol; private final double charge; Quark(char symbol, double charge){ this.symbol = symbol; this.charge = charge; } public char getSymbol(){ return symbol; } public double getCharge(){ return charge; } } Ben Abdallah Helmi Architect 56 56 J2EE
57. 57. 10. Which of the following are legal enums? A. enum Animals { LION, TIGER, BEAR } B. enum Animals { int age; LION, TIGER, BEAR; } C. enum Animals { LION, TIGER, BEAR; int weight; } D. enum Animals { LION(450), TIGER(450), BEAR; int weight; Animals(int w) { weight = w; } } E. enum Animals { LION(450), TIGER(450), BEAR; int weight; Animals() { } Animals(int w) { weight = w; } } Ben Abdallah Helmi Architect 57 57 J2EE
58. 58. 10. C, E. A is illegal because the list of names must be terminated by a semicolon. B is illegal because the list of names must be the first element in the enum body. C is a legal enum that contains, in addition to its name list, a variable. D is illegal because the declaration of Bear requires the existence of a no-args constructor. E fixes the bug in D by adding a no-args constructor. Ben Abdallah Helmi Architect 58 58 J2EE
59. 59. 12. Which of the following are true? (Choose all that apply.) • A. An enum definition should declare that it extends java.lang.Enum. • B. An enum may be subclassed. • C. An enum may contain public method definitions. • D. An enum may contain private data. Ben Abdallah Helmi Architect 59 59 J2EE
60. 60. 12. C, D. Enums may not extend or be extended. They may contain methods and data just like ordinary classes. Ben Abdallah Helmi Architect 60 60 J2EE
61. 61. 13. Which of the following are true? (Choose all that apply.) A. An enum definition may contain the main() method of an application. B. You can call an enum’s toString() method. C. You can call an enum’s wait() method. D. You can call an enum’s notify() method. Ben Abdallah Helmi Architect 61 61 J2EE
62. 62. 13. A, B, C, D. Enums may contain public static void main() methods and may serve as application main classes. Enums inherit from Object, so they have toString(), wait(), and notify() methods. Ben Abdallah Helmi Architect 62 62 J2EE
63. 63. 14. Suppose x and y are of type TrafficLightState, which is an enum. What is the best way to test whether x and y refer to the same constant? A. if (x == y) B. if (x.equals(y)) C. if (x.toString().equals(y.toString())) D. if (x.hashCode() == y.hashCode()) Ben Abdallah Helmi Architect 63 63 J2EE
64. 64. 14. A. It is never possible to have two instances of an enum that represent the same value. So the == operator is reliable, and it’s faster than any method call. Ben Abdallah Helmi Architect 64 64 J2EE
65. 65. 16. Given the following code, which of the following will compile? enum Spice { NUTMEG, CINNAMON, CORIANDER, ROSEMARY; } A. Spice sp = Spice.NUTMEG; Object ob = sp; B. Spice sp = Spice.NUTMEG; Object ob = (Object)sp; C. Object ob = new Object(); Spice sp = object; D. Object ob = new Object(); Spice sp = (Spice)object; Ben Abdallah Helmi Architect 65 65 J2EE
66. 66. 16. A, B, D. Enums may be converted to Object, just like other objects. So A and B are legal, though the cast in B is not necessary. Assigning an Object reference to an enum requires a cast, so C is illegal, but D is legal Ben Abdallah Helmi Architect 66 66 J2EE
67. 67. 18. Which methods return an enum constant’s name? A. getName() B. name() C. toString() D. nameString() E. getNameString() Ben Abdallah Helmi Architect 67 67 J2EE
68. 68. 18. B, C. Both name() and toString() return a constant’s name. name() is final, but toString() can be overridden. Ben Abdallah Helmi Architect 68 68 J2EE
69. 69. 69
70. 70. 70
71. 71. 71
72. 72. 72
73. 73. 73
74. 74. 74
75. 75. 75
76. 76. 76
77. 77. 77
78. 78. 78
79. 79. 79
80. 80. 80
81. 81. 81
82. 82. 82
83. 83. 83