Thinking in Java(7)——Reusing classes

Composition syntax

  • 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.
  • Initialize references
  • At the point the objects are defined. This means that they’ll always be initialized
    before the constructor is called.
  • In the constructor for that class.
  • Right before you actually need to use the object. 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.
  • Using instance initialization.

Inheritance syntax

extends

Initializing the base class
  • 默认地,先调用基类构造器,再调用导出类构造器
  • 如果基类构造器含参,在导出类构造器中未采取super(参数)方式调用,则编译出错。(There is no default constructor available…)

Delegation

Midway between inheritance and composition.
Place a member object in the class you’re building, but at the same time expose all the methods from the member object in your new class.
You have more control with delegation rather than inheritance because you can choose to provide only a subset of the methods in the member object.

Combining composition and inheritance

Guranteeing proper cleanup

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

Name hiding

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.(Compile time error)

Choosing composition vs. inheritance

  • Composition
    * Explicitly place subobjects inside new class
    * Generally used when you want the features of an existing class inside your new class, but not its interface.
  • Inheritance: develop a special version of the existing class.

Upcasting

class Instrument{
	public void play(){}
	static void tune(Instrument i){
		//...
		i.play();
	}
}

//Wind objects are instruments
//Because they have the same interface
public class Wind extends Instrument{
	public static void main(String[] args){
		Wind flute = new Wind();
		Instrument.tune(flute);//Upcasting
	}
}

The final keyword

This cannot be changed.

final data
  • It can be a complie-time constant that won’t change
  • It can be a value initialized at run time that you don’t want changed.
  • For 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. A value must be given at the time of definition of such a constant.
  • A field is both static and final has only one piece of storage that cannot be changed.
  • Fields that are both static and final (that is, compile-time constants) are capitalized and use underscores to separate words.
  • 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.
  • Blank finals
  • Java allows the creation of blank finals, which are fields that are declared as final but are not given an initialization value.
  • You’re forced to perform assignments to finals either with an expression at the point of definition of the field or in every constructor.
  • Final arguments
    • 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 what the argument reference points.
    • This feature is primarily used to pass data to anonymous inner classes
Final methods

Reasons:

  • 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.
  • 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. 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.
    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.
  • Any private methods in a class are implicitly final
Final classes

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.
Because it prevents inheritance, all methods in a final class are implicitly final, since there’s no way to override them.

Initialization and class loading

  • “class code is loaded at the point of first use.” Usually when the first object of that class is constructed, but loading also occurs when a static field or static method is accessed.
  • The point of first use is also where the static initialization takes place.
  • All the static objects and the static code block will be initialized in textual order.
Initialization with inheritance
  1. Access “main” method
  2. Find the compiled code for the class.
  3. If loader notices there is a base class, then it tries to make an object of the base class.
  4. After all necessary classes are loaded, all
    the primitives in this object are set to their default values and the object references are set to null.
  5. Then the base-class constructor will be called. In this case the call is automatic, but you can also specify the base-class constructor call by
    using super. The base class construction goes through the same process in the same order as the derived-class constructor.
  6. After the base-class constructor completes, the instance variables are initialized in textual order.
  7. Finally, the rest of the body of the constructor is
    executed.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值