Reusing Classes


  • The first is composition,You’re simply reusing the functionality of the code, not its form.
  • The second approach is inheritance,You literally take the form of the existing class and add code to it without modifying the existing class.

Composition syntax

  • You simply place object references inside new classes.

  • Every non-primitive object has a toString( ) method.

  • If you want the references initialized, you can do it:

    1.At the point the objects are defined.

    2.In the constructor for that class.

    3.Right before you actually need to use the object(lazy initialization).

    4.Using instance initialization.

Inheritance syntax

  • It turns out that you’re always doing inheritance when you create a class.
  • You automatically get all the fields and methods in the base class.
  • This technique of putting a main() in each class allows easy testing for each class.
  • Even if a class has package access, a public main() is accessible.
  • If a class from some other package were to inherit from base class, it could access only public members.
  • To allow for inheritance, as a general rule make all fields private and all methods public.
  • It’s possible to take a method that’s been defined in the base class and modify it.
  • Java has the keyword super that refers to the “superclass” that the current class inherits.

Initializing the base class

  • It can be a bit confusing to try to imagine the resulting object produced by a derived class.
  • When you create an object of the derived class, it contains within it a subobject of the base class.
  • Perform the initialization in the constructor by calling the base- class constructor
  • Java automatically inserts calls to the base-class constructor in the derived-class constructor.
  • The compiler will synthesize a default constructor for you that calls the base class constructor.

Constructors with arguments

  • If your class doesn’t have default arguments, 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.
  • The call to the base-class constructor must be the first thing you do in the derived-class constructor.

Delegation

  • 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).
  • Although the Java language doesn’t support delegation, development tools often do.

Combining composition and inheritance

  • The compiler doesn’t watch over you to make sure that you initialize the member objects, so you must remember to pay attention to that.
  • You don’t even need the source code for the methods in order to reuse the code. At most, you just import a package.

Guaranteeing proper cleanup

  • So if you want something cleaned up for a class, you must explicitly write a special method to do it, and make sure that the client programmer knows that they must call this method.
  • First perform all of the cleanup work specific to your class, in the reverse order of creation. Then call the base-class cleanup method.
  • when you must do cleanup explicitly, diligence and attention are required, because there’s not much you can rely on when it comes to garbage collection.

Name hiding

  • Overloading works regardless of whether the method was defined at this level or in a base class.
  • It’s far more common to override methods of the same name, using exactly the same signature and return type as in the base class.
  • You can choose to add this annotation and the compiler will produce an error message if you accidentally overload instead of overriding.

Choosing composition vs. inheritance

  • 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.
  • When you inherit, you’re taking a general-purpose class and specializing it for a particular need.
  • The is-a relationship is expressed with inheritance, and the has-a relationship is expressed with composition.

protected

  • You want to make something hidden from the world at large and yet allow access for members of derived classes.

Upcasting

  • The new class is a type of the existing class.
  • Any message you can send to the base class can also be sent to the derived class.

Why “upcasting”?

  • Casting from a derived type to a base type moves up on the inheritance diagram, so it’s commonly referred to as upcasting.
  • Upcasting is always safe because you’re going from a more specific type to a more general type.
  • It can lose methods, not gain them.
  • The compiler allows upcasting without any explicit casts or other special notation.

Composition vs. inheritance revisited

  • You should use it sparingly, only when it’s clear that inheritance is useful.
  • Whether you’ll ever need to upcast from your new class to the base class.

The final keyword

  • Java’s final keyword has slightly different meanings depending on the context

final data

  • A value must be given at the time of definition of such a constant.
  • With a primitive, final makes the value a constant, but with an object reference, final makes the reference a constant.
  • However, the object itself can be modified.
  • Java does not provide a way to make any arbitrary object a constant.
  • Just because something is final doesn’t mean that its value is known at compile time.
  • The difference between making a final value static or non-static.
  • There is no way that I know of to make the array references themselves final.

Blank finals

  • The blank final must be initialized before it is used, and the compiler ensures this.
  • 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.

final arguments

  • This means that inside the method you cannot change what the argument reference points to.
  • You can read the argument, but you can’t change it.
  • This feature is primarily used to pass data to anonymous inner classes.

final methods

  • Final methods put a “lock” on the method to prevent any inheriting class from changing its meaning.
  • You want to make sure that a method’s behavior is retained during inheritance and cannot be overridden.

final and private

  • Any private methods in a class are implicitly final.
  • If a method is private, it isn’t part of the base-class interface.
  • You haven’t overridden the method; you’ve just created a new method.

final classes

  • You don’t want to inherit from this class or allow anyone else to do so.
  • Note that the fields of a final class can be final or not.
  • Bnecause it prevents inheritance, all methods in a final class are implicitly final.

final caution

  • If you define a method as final, you might prevent the possibility of reusing your class through inheritance in some other programmer’s project simply because you couldn’t imagine it being used that way.

Initialization and class loading

  • The compiled code for each class exists in its own separate file. That file isn’t loaded until the code is needed.
  • class code is loaded at the point of first use.
  • Loading also occurs when a static field or static method is accessed.

Initialization with inheritance

  • The static initialization in the root base class (in this case, Insect) is performed, and then the next derived class, and so on.
  • First, all the primitives in this object are set to their default values and the object references are set to null.
  • Then the base-class constructor will be called.
  • The instance variables are initialized in textual order.
  • Finally, the rest of the body of the constructor is executed.

Thinking in Java——笔记(7)的更多相关文章

  1. Effective Java笔记一 创建和销毁对象

    Effective Java笔记一 创建和销毁对象 第1条 考虑用静态工厂方法代替构造器 第2条 遇到多个构造器参数时要考虑用构建器 第3条 用私有构造器或者枚举类型强化Singleton属性 第4条 ...

  2. java笔记00-目录

    --2013年7月26日17:49:59 学习java已久,趁最近有空,写一个总结: java笔记01-反射:

  3. java笔记整理

    Java 笔记整理 包含内容     Unix Java 基础, 数据库(Oracle jdbc Hibernate pl/sql), web, JSP, Struts, Ajax Spring, E ...

  4. 转 Java笔记:Java内存模型

    Java笔记:Java内存模型 2014.04.09 | Comments 1. 基本概念 <深入理解Java内存模型>详细讲解了java的内存模型,这里对其中的一些基本概念做个简单的笔记 ...

  5. servlet(6) - servlet总结 - 小易Java笔记

    垂阅前必看: 这都是我总结的我觉得是学习servlet应该掌握的,我在学习期间也做了一个博客项目来让所学的知识得以巩固.下面就是博客项目链接.前面的servlet相关的笔记总汇,还有就是我把觉得在学习 ...

  6. Java笔记 —— 继承

    Java笔记 -- 继承 h2{ color: #4ABCDE; } a{ text-decoration: none!important; } a:hover{ color: red !import ...

  7. Java笔记 —— 方法重载和方法重写

    Java笔记 -- 方法重载和方法重写 h2{ color: #4ABCDE; } a{ text-decoration: none !important; } a:hover{ color: red ...

  8. Java笔记 —— 初始化

    Java笔记 -- 初始化 h2{ color: #4ABCDE; } a{ text-decoration: none !important; } a:hover{ color: red !impo ...

  9. Java笔记 —— this 关键字

    Java笔记 -- this 关键字 h2{ color: #4ABCDE; } a{ color: blue; text-decoration: none; } a:hover{ color: re ...

  10. Java 笔记 —— java 和 javac

    Java 笔记 -- java 和 javac h2{ color: #4ABCDE; } a{ text-decoration: none !important; } a:hover{ color: ...

随机推荐

  1. js动画实现透明度动画

    在本次实例中,由于一般主流的浏览器对于透明度opacity最大值为1,但是在IE6最大值是100,此次例子是按主流浏览器的透明度来算的,所以定义的是小数,也可以定义为整数为单位,在运算的时候遇到主流的 ...

  2. http://blog.csdn.net/hitmediaman/article/details/6636402

    http://blog.csdn.net/hitmediaman/article/details/6636402

  3. 使用GDB 修改MySQL参数不重启

    link:http://blog.chinaunix.net/uid-20785090-id-4016315.html mysql很多参数都需要重启才能生效,有时候条件不允许,可以使用gdb作为最后的 ...

  4. HDU 2831 (贪心)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2831 题目大意:植物大战僵尸.给定种植植物时间间隔t,以及每个僵尸的到达时间v,生命d.问是否能赢. ...

  5. jq prepend() 方法在被选元素的开头(仍位于内部)插入指定内容。 提示:prepend() 和 prependTo() 方法作用相同。差异在于语法:内容和选择器的位置,以及 prependTo() 无法使用函数来插入内容。

    <html><head><script type="text/javascript" src="/jquery/jquery.js" ...

  6. codeforces Round #252 (Div. 2) C - Valera and Tubes

    贪心算法,每条路径最短2格,故前k-1步每次走2格,最后一步全走完 由于数据比较小,可以先打表 #include <iostream> #include <vector> #i ...

  7. NOIp 2014 #2 联合权值 Label:图论 !!!未AC

    题目描述 无向连通图G 有n 个点,n - 1 条边.点从1 到n 依次编号,编号为 i 的点的权值为W i ,每条边的长度均为1 .图上两点( u , v ) 的距离定义为u 点到v 点的最短距离. ...

  8. JavaScript进阶篇

    组团,并给团取个名(如何创建数组) 使用数组之前首先要创建,而且需要把数组本身赋至一个变量.好比我们出游,要组团,并给团定个名字“云南之旅”. 创建数组语法: var myarray=new Arra ...

  9. 【BZOJ2186】【SDoi2008】沙拉公主的困惑 数论

    Description 大富翁国因为通货膨胀,以及假钞泛滥,政府决定推出一项新的政策:现有钞票编号范围为1到N的阶乘,但是,政府只发行编号与M!互质的钞票.房地产第一大户沙拉公主决定预测一下大富翁国现 ...

  10. BZOJ3293: [Cqoi2011]分金币

    Description 圆桌上坐着n个人,每人有一定数量的金币,金币总数能被n整除.每个人可以给他左右相邻的人一些金币,最终使得每个人的金币数目相等.你的任务是求出被转手的金币数量的最小值. Inpu ...