JHTP小结_第八章_深入理解类和对象

时间:2021-10-15 18:32:56



Summary


Section 8.2 TimeClass Case Study


• The public methods of aclass are also known as the class’s public services or public interface (p.316). They present to the class’s clients a view of the services the classprovides.


• A class’s private members arenot accessible to its clients.


String class static method format (p. 318) issimilar to method System.out.printf except that format returns aformatted String rather than displaying it in a command window.


• All objects in Javahave a toString method that returns a String representationof the object.


Method toString is calledimplicitly when an object appears in code where a String is needed.


Section 8.3Controlling Access to Members


• The access modifiers public and private controlaccess to a class’s variables and methods.


• The primary purpose of public methods is topresent to the class’s clients a view of the services the class provides.Clients need not be concerned with how the class accomplishes its tasks.


• A class’s private variables andprivate methods (i.e., its implementation details) are not accessible toits clients.


Section 8.4Referring to the Current Object’s Members with the thisReference


• An instance method ofan object implicitly uses keyword this (p. 322) torefer to the object’s instance variables and other methods. Keyword this can also beused explicitly.


• The compiler produces aseparate file with the .class extension for every compiled class.


• If a local variable hasthe same name as a class’s field, the local variable shadows the field. You canuse the this reference in a method to refer to the shadowed field explicitly.


Section 8.5 TimeClass Case Study: Overloaded Constructors


• Overloaded constructorsenable objects of a class to be initialized in different ways. The compiler


differentiates overloadedconstructors (p. 324) by their signatures.


• To call one constructorof a class from another of the same class, you can use the this keyword


followed by parenthesescontaining the constructor arguments. If used, such a constructor call


must appear as the firststatement in the constructor’s body.


Section 8.6Default and No-Argument Constructors


• If no constructors areprovided in a class, the compiler creates a default constructor.


• If a class declaresconstructors, the compiler will not create a default constructor. In this case,you


must declare ano-argument constructor (p. 327) if default initialization is required.


Section 8.7 Noteson Set and Get Methods


Set methods arecommonly called mutator methods (p. 331) because they typically change a value.


Get methods arecommonly called accessor methods (p. 331) or query methods. A predicate method(p. 332) tests whether a condition is true or false.


Section 8.8Composition


• A class can havereferences to objects of other classes as members. This is called composition (p.332) and is sometimes referred to as a has-a relationship.


Section 8.9 enumTypes


• All enum types (p.335) are reference types. An enum type is declared with an enum declaration, whichis a comma-separated list of enum constants. The declarationmay optionally include other components of traditional classes, such asconstructors, fields and methods.


enum constants areimplicitly final, because they declare constants that should not be modified.


enum constants areimplicitly static.


• Any attempt to createan object of an enum type with operator new results in acompilation error.


enum constants canbe used anywhere constants can be used, such as in the case labels of switch statementsand to control enhanced for statements.


• Each enum constant inan enum declaration is optionally followed by arguments which are passedto the enum constructor.


• For every enum, thecompiler generates a static method called values (p. 336) that returns an arrayof the enum’s constants in the order in which they were declared.


EnumSetstatic method range (p. 337) receives the first and last enum constants ina range and returns an EnumSet that contains all the constants between these two constants,inclusive.


Section 8.10Garbage Collection


• The Java VirtualMachine (JVM) performs automatic garbage collection (p. 338) to reclaim the memoryoccupied by objects that are no longer in use. When there are no morereferences to an object, the object is eligible for garbage collection. Thememory for such an object can be reclaimed when the JVM executes its garbagecollector.


Section 8.11 staticClass Members


• A static variable (p.338) represents classwide information that’s shared among the class’s objects.


static variableshave class scope. A class’s public static members can beaccessed through a reference to any object of the class, or they can beaccessed by qualifying the member name with the class name and a dot (.). Clientcode can access a class’s private static class members only through methods of the class.


static class membersexist as soon as the class is loaded into memory.


• A method declared static cannot accessa class’s instance variables and instance methods, because a static method can becalled even when no objects of the class have been instantiated.


• The this referencecannot be used in a static method.


Section 8.12 staticImport


• A static importdeclaration (p. 342) enables you to refer to imported static memberswithout the class name and a dot (.). A single static importdeclaration imports one static member, and a static import on demand importsall static members of a class.


Section 8.13 finalInstance Variables


• In the context of anapp’s code, the principle of least privilege (p. 343) states that code shouldbe granted only the amount of privilege and access that it needs to accomplishits designated task.


• Keyword final specifiesthat a variable is not modifiable. Such variables must be initialized when they’redeclared or by each of a class’s constructors.


Section 8.14Package Access


• If no access modifieris specified for a method or variable when it’s declared in a class, the methodor variable is considered to have package access (p. 344).


Section 8.15 UsingBigDecimal for Precise Monetary Calculations


• Any application thatrequires precise floating-point calculations without rounding errors—such as thosein financial applications—should instead use class BigDecimal(package java.math; p. 346).


BigDecimalstatic method valueOf (p. 347) with a double argument returns a BigDecimalthat represents the exact value specified.


BigDecimalmethod add (p. 347) adds its argument BigDecimal to the BigDecimalon which the method is called and returns the result.


BigDecimalprovides the constants ONE (1), ZERO (0) and TEN (10).


BigDecimalmethod pow (p. 347) raises its first argument to the power specified in itssecond argument.


BigDecimalmethod multiply (p. 347) multiplies its argument BigDecimal with the BigDecimalon which the method is called and returns the result.


• Class NumberFormat(package java.text; p. 347) provides capabilities for formatting numeric values aslocale-specific Strings. The class’s static method getCurrencyInstancereturns a preconfigured


NumberFormat forlocal-specific currency values. NumberFormat method format performs theformatting.


• Locale-specificformatting is an important part of internationalization—the process ofcustomizing your applications for users’ various locales and spoken languages.


BigDecimalgives you control over how values are rounded—by default allcalculations are exact and no rounding occurs. If you do not specify how toround BigDecimal values and a given value cannot be represented exactly an ArithmeticExceptionoccurs.


• You can specify therounding mode for BigDecimal by supplying a MathContext object (package java.math) to class BigDecimal’sconstructor when you create a BigDecimal. You may also provide a MathContextto various BigDecimal methods that perform calculations. By default, each pre-configuredMathContext uses so called “bankers rounding.”


• A BigDecimal’s scale isthe number of digits to the right of its decimal point. If you need a Big-Decimalrounded to a specific digit, you can call BigDecimalmethod setScale.