`
leonzhx
  • 浏览: 791703 次
  • 性别: 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

分享到:
评论

相关推荐

    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 ...

    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

    thinking in Java guide solutio

    根据提供的文件信息,我们可以将《Thinking in Java》第四版中的主要内容和知识点进行详细的解析与总结。本书由Bruce Eckel编写,是学习Java编程语言的经典教材之一。以下是对书中的几个关键章节及其涵盖的重要知识...

    Thinking in Java 4th Edition with Annotated Solution Guide编程思想+课后习题源码

    7. **Innerclasses**:内部类是Java中一个独特的特性,它可以是成员内部类、局部内部类、匿名内部类或静态内部类。内部类可以更好地实现封装,同时在某些特定情况下提供更灵活的设计选择。 8. **Initialization**:...

    sap query -bcsrvque

    ##### 7. Output List Display - **定义**:Output List Display 指的是查询结果的列表形式展示。 - **特点**: - 可以清晰地查看每一条数据记录。 - 支持多种排序方式,方便查找特定的信息。 ##### 8. ...

    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...

    scipylectures

    #### Advanced Python Constructs (Chapter 7) - **Iterators, Generator Expressions, and Generators:** Efficiently iterating over large datasets and generating values on-the-fly. - **Decorators:** ...

    Thinking_In_C#英文正式版

    第7章“Reusing Classes”(类的重用)讲述了如何通过继承和多态性来重用代码,同时第8章“Interfaces and Implementation”(接口与实现)阐述了接口的重要性以及如何实现和使用接口。第9章“Collecting Your ...

    Thinking in CSharp

    - **第七章:重用类**(Reusing classes):探讨了如何通过继承和组合等方式重用现有类的功能,这有助于减少重复代码并提高开发效率。 - **第八章:接口与实现**(Interfaces and Implementation):详细介绍了C#中...

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

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

    Unity ScrollView 组件扩展实例Demo Unity可直接运行

    2. **Reusing Cells**:为了提高性能,ScrollView 实现了 Cell 回收机制,即当一个 Item 不再可视时,它会被标记为待复用,并存储在池中,供后续创建新 Item 时复用,而不是每次都新建。 3. **Data Binding**:每个 ...

Global site tag (gtag.js) - Google Analytics