Thinking in Java 读书笔记(1)

来源:互联网 发布:阿里云vpn 编辑:程序博客网 时间:2024/05/22 03:33

第一章:对象导论

面向对象程序设计五个基本特性:

1、 Everything is a object. Think of a object as a fancy variable;it stores data,but you can “make requests” to that object,asking it to perform operations on itself.In theory,you can take any conceptual component in the problem you’re trying to solve and represent it as an object in your program.

2、A program is a bunch of objects telling each other what to do by sending messages. To make a request of an object, you “send a message” to that object. More concretely, you can think of a message as a request to call a method that belongs to a particular object.

3、Each object has its own memory made up of other objects. Put another way, you create a new kind of object by making a package containing existing objects. Thus, you can build complexity into a program while hiding it behind the simplicity of objects.

4、Every object has a type. Using the parlance, each object is an instance of a class, in which “class” is synonymous with “type.” The most important distinguishing characteristic of a class is “What messages can you send to it?”

5、All objects of a particular type can receive the same messages. This is actually a loaded statement, as you will see later. Because an object of type “circle” is also an object of type “shape,” a circle is guaranteed to accept shape messages. This means you can write code that talks to shapes and automatically handle anything that fits the description of a shape. This substitutability is one of the powerful concepts in OOP

一个对象还包括状态、行为、特性。类是具有相同特性(数据元素)和行为(功能)的对象的集合。它是一种数据类型。每个对象都只满足某些请求,这些请求由对象的接口(Interface)所定义,决定接口的便是类型。

   每一对象都提供服务,将对象看作服务提供者

隐藏具体实现

   访问控制:

作用域

当前类

同一package

子孙类

其他package

public

protected

×

friendly

×

×

private

×

×

×

复用具体实现:

    1、创建新类时首先考虑组合而不是继承

2、继承复用接口

继承现有类型时,也就创造了新的类型。这个新的类型不仅包括现有类型的所有成员(尽管private成员被隐藏起来并且不可访问),更重要的是它复制了基类的接口,所有可以发送给基类对象的消息同时也可以发送给导出类,意味着导出类与基类有相同的类型

3、重载(Overriding

导出类重新定义基类中的方法,使之在新类型中可以完成不同的任务。

导出类完全替代基类中的方法,是is-a的关系;导出类中添加新方法而基类无法访问,是is-like-a关系;

4、多态

不依赖于特定类型的代码就是把一个对象不当作它所属的特定类型来对待,而是将其当作基类的对象来对待。在OOP中,程序直道运行时刻才能够确定代码的地址,所以当消息发送到一个范化对象时,采用“后期绑定(late binding)”

。当向对象发送消息时,被调用代码直到运行时刻才能被确定,编译器确保被调用方法存在,并对调用参数(argument)和返回值(return value)执行类型检查(无法提供此类保证的语言称作弱类型),但是并不知道确切要执行的代码。

Java中使用一小段代码来替代绝对地址调用,实现后期绑定。

向上转型(upcasting

    5、抽象基类和接口

不希望任何人创建基类的实际对象,只是希望对象向上转型到基类,就使用接口。使用abstract关键字来标识抽象类,也可以表示尚未被实现的方法。

抽象方法只能在抽象类中实现,当该类被继承时抽象方法必须被实现,否则继承类依然是抽象类。

Interface根本不容许有任何方法定义。

对象的创建、使用和生命周期

分为两种方式:

1、为了追求最大的执行速度,对象的存储空间和生命周期在编写程序时确定。通过将对象置于堆栈或静态存储区内来实现。

2、在被称作堆的内存池中动态地创建对象,垃圾收集机制。直到运行时刻才知道需要多少对象、它们的生命周期、它们的具体类型,只有在程序运行时相关代码被执行到的那一刻才能确定。

单根继承结构

    所有的类都继承自一个基类

 
原创粉丝点击