`
leonzhx
  • 浏览: 768306 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Chapter 7. Reusing Classes -- Thinking in Java

阅读更多

1) You have two ways to use the classes without soiling the existing code:

    a. you simply create objects of your existing class inside the new class. This is called composition, because the new class is composed of objects of existing classes. You’re simply reusing the functionality of the code, not its form.
    b. You create a new class as a type of an existing class. You literally take the form of the existing class and add code to it without modifying the existing class. This technique is called inheritance, and the compiler does most of the work. Inheritance is one of the cornerstones of object-oriented programming.

 

2) Every non-primitive object has a toString( ) method, and it’s called in special situations when the compiler wants a String but it has an object. Conveniently, you can still print a null reference without throwing an exception.

 

3) You have the following ways to have the fields initialized:
    a. At the point the fields are defined. This means that they’ll always be initialized before the constructor is called.
    b. In the constructor for that class.
    c. Right before you actually need to use the field. This is often called lazy initialization. It can reduce overhead in situations where object creation is expensive and the object doesn’t need to be created every time.
    d. Using instance initialization.

 

4) Inheritance is an integral part of Java (and all OOP languages). It turns out that you’re always doing inheritance when you create a class, because unless you explicitly inherit from some other class, you implicitly inherit from Java’s standard root class Object.

 

5) When you inherit, you say “This new class is like that old class.” You state this in code before the opening brace of the class body, using the keyword extends followed by the name of the base class. When you do this, you automatically get all the fields and methods in the base class.

 

6) Even if you have a lot of classes in a program, only the main( ) for the class invoked on the command line will be called.

 

7) It’s possible to take a method that’s been defined in the base class and modify it. In this case, you might want to call the method from the base class inside the new version. To solve this problem, Java has the keyword super that refers to the “superclass” that the current class inherits.

 

8) When inheriting you’re not restricted to using the methods of the base class. You can also add new methods to the derived class exactly the way you put any method in a class.

 

9) Inheritance doesn’t just copy the interface of the base class. When you create an object of the derived class, it contains within it a subobject of the base class. This subobject is the same as if you had created an object of the base class by itself. It’s just that from the outside, the subobject of the base class is wrapped within the derived-class object.

 

10) Of course, it’s essential that the base-class subobject be initialized correctly, and there’s only one way to guarantee this: Perform the initialization in the constructor by calling the base-class constructor, which has all the appropriate knowledge and privileges to perform the base-class initialization. Java automatically inserts calls to the base-class constructor in the derived-class constructor. The base class subobject is initialized before the derived-class constructors can access it.

 

11) If your base-class doesn’t have default constructor, or if you want to call a base-class constructor that has an argument, you must explicitly write the calls to the base-class constructor using the super keyword and the appropriate argument list. If you don't and  the compiler cannot find the default constructor of the base-class , it will complain.(You can also call another constructor which already calls the base-class's constructor.)  In addition, the call to the base-class constructor (or the call to another constructor) must be the first thing you do in the derived-class constructor. (The compiler will remind you if you get it wrong.)

 

12) A third relationship, which is not directly supported by Java, is called delegation. This is midway between inheritance and composition, because you place a member object in the class you’re building (like composition), but at the same time you expose all the methods from the member object in your new class (like inheritance).

 

13) Note that in your cleanup method, you must also pay attention to the calling order for the base-class and member-object cleanup methods in case one subobject depends on another. In general, you should first perform all of the cleanup work specific to your class, in the reverse order of creation. (In general, this requires that base-class elements still be viable.) Then call the base-class cleanup method.

 

14) There’s not much you can rely on when cleanup comes to garbage collection. The garbage collector might never be called. If it is, it can reclaim objects in any order it wants. You can’t rely on garbage collection for anything but memory reclamation. If you want cleanup to take place, make your own cleanup methods and don’t use on finalize( ).

 

15) You can overload methods of base class in derived class and those methods of base class will still be available in derived class. Java SE5 has added the @Override annotation, which is not a keyword but can be used as if it were. When you mean to override a method, you can choose to add this annotation and the compiler will produce an error message if you accidentally overload instead of overriding.

 

16) Composition is generally used when you want the features of an existing class inside your new class, but not its interface. That is, you embed an object so that you can use it to implement features in your new class, but the user of your new class sees the interface you’ve defined for the new class rather than the interface from the embedded object. For this effect, you embed private objects of existing classes inside your new class.

 

17) The is-a relationship is expressed with inheritance, and the has-a relationship is expressed with composition.

 

18) Because inheritance means that all of the methods in the base class are also available in the derived class, any message you can send to the base class can also be sent to the derived class. This means the new class is a type of the existing class.

 

19)  The act of converting a derived class object reference into an base class object reference is called upcasting. Casting from a derived type to a base type moves up on the inheritance diagram, so it’s commonly referred to as upcasting.

 

20) One of the clearest ways to determine whether you should use composition or inheritance is to ask whether you’ll ever need to upcast from your new class to the base class. If you must upcast, then inheritance is necessary, but if you don’t need to upcast, then you should look closely at whether you need inheritance.

 

21) A constant is useful for two reasons:
    a. It can be a compile-time constant that won’t ever change.
    b. It can be a value initialized at run time that you don’t want changed.

 

22) In the case of a compile-time constant, the compiler is allowed to “fold” the constant value into any calculations in which it’s used; that is, the calculation can be performed at compile time, eliminating some run-time overhead. In Java, these sorts of constants must be primitives and are expressed with the final keyword. A value must be given at the time of definition of such a constant.

 

23) With a primitive, final makes the value a constant, but with an object reference, final makes the reference a constant. Once the reference is initialized to an object, it can never be changed to point to another object. However, the object itself can be modified; Java does not provide a way to make any arbitrary object a constant.

 

24) By convention, fields that are both static and final primitives with constant initial values (that is, compile-time constants) are capitalized and use underscores to separate words.

 

25) The difference between a static final value and non-static final value show up only when the values are initialized at run time ( through runtime method ), since the compile-time values are treated the same by the compiler.

 

26) Java allows the creation of blank finals, which are fields that are declared as final but are not given an initialization value. In all cases, the blank final must be initialized before it is used, and the compiler ensures this. However, blank finals provide much more flexibility in the use of the final keyword since, for example, a final field inside a class can now be different for each object, and yet it retains its immutable quality. You’re forced to perform assignments to finals either with an expression at the point of definition of the field or in every constructor.

 

27) Java allows you to make arguments final by declaring them as such in the argument list. This means that inside the method you cannot change the argument value. This feature is primarily used to pass data to anonymous inner classes.

 

28) There are two reasons for final methods. The first is to put a “lock” on the method to prevent any inheriting class from changing its meaning. This is done for design reasons when you want to make sure that a method’s behavior is retained during inheritance and cannot be overridden. The second reason for final methods is efficiency. In earlier implementations of Java, if you made a method final, you allowed the compiler to turn any calls to that method into inline calls. When the compiler saw a final method call, it could (at its discretion) skip the normal approach of inserting code to perform the method call mechanism (push arguments on the stack, hop over to the method code and execute it, hop back and clean off the stack arguments, and deal with the return value) and instead replace the method call with a copy of the actual code in the method body. This eliminated the overhead of the method call. Of course, if a method is big, then your code begins to bloat, and you probably wouldn’t see any performance gains from inlining, since any improvements will be dwarfed by the amount of time spent inside the method.
In more recent version of Java, the virtual machine (in particular, the hotspot technologies) can detect these situations and optimize away the extra indirection, so its no longer necessary-in fact, it is now generally discouraged-to use final to try to help the optimizer. With Java SE5/6, you should let the compiler and JVM handle efficiency issues and make a method final only if you want to explicitly prevent overriding.

 

29) Any private methods in a class are implicitly final. Because you can’t access a private method, you can’t override it. You can add the final specifier to a private method, but it doesn’t give that method any extra meaning.

 

30) If a method is private, it isn’t part of the base-class interface. It is just some code that’s hidden away inside the class, and it just happens to have that name, but if you create a public, protected, or package-access method with the same name in the derived class, there’s no connection to the method that might happen to have that name in the base class. You haven’t overridden the method; you’ve just created a new method.

 

31) When you say that an entire class is final (by preceding its definition with the final keyword), you state that you don’t want to inherit from this class or allow anyone else to do so. In other words, for some reason the design of your class is such that there is never a need to make any changes, or for safety or security reasons you don’t want subclassing. All methods in a final class are implicitly final, since there’s no way to override them. You can add the final specifier to a method in a final class, but it doesn’t add any meaning.

 

32) The constructor is also a static method even though the static keyword is not explicit. So to be precise, a class is first loaded when any one of its static members is accessed.

 

33) The static initialization in the root base class is performed, and then the next derived class, and so on. This is important because the derived-class static initialization might depend on the base class member being initialized properly.

 

34) Initilization order : base class static fields --> derived class static fields --> base class non-static fields --> base class constructor --> derived class non-static fields --> derived class constructor

分享到:
评论

相关推荐

    Thinking in JAVA 4th英文版

    Thinking in Java Fourth Edition Bruce Eckel 以下目录 是直接从pdf 中复制的: What’s Inside Preface 1 Java SE5 and SE6 .................. 2 Java SE6 ......................................... 2 The 4 ...

    Thinking in Java 4th Edition

    Arrays in Java .............................. 44 You never need to destroy an object .................. 45 Scoping ........................................ 45 Scope of objects ...........................

    Thinking+in+Java+4th+Edition

    Thinking+in+Java+4th+Edition english.pdf Preface 1 Java SE5 and SE6 .................. 2 Java SE6 ......................................... 2 The 4 edition........................ 2 th Changes .........

    EI333 软件工程-Software Engineering-全套 PPT 课件

    7.System Design-Addressing Design Goals.pptx 8. Object Design-Reusing Pattern Solutions.pptx 9. Object Design-Specifying Interfaces.pptx 10.Mapping Models to Code.pptx 11.Testing(S).pptx 词汇表.docx ...

    TIJ4Reusing Classes

    thinking in java 4 Reusing Classes 读书笔记

    Testing and Quality Assurance for Component-Based Software

    Reusing high-quality software components in software development has the poten- tial for drastically improving the quality and development productivity of component-based software. However, the ...

    SAS® 9.1 Macro Language.pdf

    Chapter 7. . . . . . . . . .Macro Quoting 75 Chapter 8. . . . . . . . . .Interfaces with the Macro Facility 95 Chapter 9. . . . . . . . . .Storing and Reusing Macros 105 Chapter 10. . . . . . . . ....

    Thinking In Java 4th Edition.pdf

    Reusing Classes 165  Polymorphism 193  Interfaces 219  Inner Classes 243  Holding Your Objects 275  Error Handling with Exceptions 313  Strings 355  Type Information 393  .... ....

    Deliver.Audacious.Web.Apps.with.Ember2

    It's time for web development to be fun again, time to write ...Chapter 7. Reusing Code in Ember Chapter 8. Building, Testing, and Deploying Your Ember Apps Chapter 9. Building and Using Ember Addons

    Practical Mod Perl

    References Part II: mod_perl Performance Chapter 7. Identifying Your Performance Problems Section 7.1. Looking at the Big Picture Section 7.2. Asking the Right Questions...

    Csharp.24-Hour.Trainer.2nd.Edition.111906566

    Quickly learn to program in C# programming with this unique book and video package C# 24-Hour Trainer, 2nd Edition is your quick and easy guide to programming in C#, even if you have no programming ...

    JavaEE 5.0 Tutorial.pdf

    The Java EE 5Tutorial For Sun Java System Application Server 9.1 Contents Preface .........................................................................................................................

    [傻瓜编程系列].Java.2.for.Dummies.pdf

    With Java trainer Barry Burd showing you the way, you’ll be creating your first Java application in no time! Discover how to: * Think like an object-oriented programmer * Save time by reusing code...

    Making Games with Python & PyGame.pdf(with code)

    Chapter 1 – Installing Python and Pygame ...................................................................................... 1 What You Should Know Before You Begin ..................................

    Learning Python, 3rd Edition

    - Python's basic procedural tool for structuring and reusing code Modules -- packages of statements, functions, and other tools organized into larger components Classes and OOP -- Python's optional ...

    Learning.Underscore.js.178439381

    Explore the Underscore.js library by example using a test-driven development approach About This Book Understand and learn to apply ...Chapter 7: Underscore.js Build Automation and Code Reusability

    Python.Descriptors

    Chapter 7: Storing the Attributes Chapter 8: Read-Only Descriptors Chapter 9: Writing __delete__() Chapter 10: Descriptors are Classes Too Chapter 11: Reusing the Wheel Chapter 12: Other Uses of ...

    PHP.and.MySQL.Web.Development.5th.Edition

    Chapter 5 Reusing Code and Writing Functions Chapter 6 Object-Oriented PHP Chapter 7 Error and Exception Handling Part II: Using MySQL Chapter 8 Designing Your Web Database Chapter 9 Creating Your ...

    Learning Python

    Classes and OOP, Python's optional object-oriented programming tool for structuring code for customization and reuse; and, Exceptions and Tools, exception handling model and statements, plus a look ...

Global site tag (gtag.js) - Google Analytics