codecamp
chapter 1 Introduction to Objects

Object oriented languages use the concept of late binding. To perform late binding, Java uses a special bit of code in lieu of the absolute call. This code calculates the address of the method body, using information stored in the object.

In some languages you must explicitly state that you want a method to have the flexibility of latebinding properties (C++ uses the virtual keyword to do this). In these languages, by default, methods are not dynamically bound. In Java,dynamic binding is the default behavior and you don’t need to remember to add any extra keywords in order to get polymorphism.Object-oriented programming (OOP) use the computer as an expressive medium.

This chapter will introduce you to the basic concepts of OOP, including an overview of development methods.


1.1 The progress of abstraction (抽象过程)

By “kind” I mean, “What is it that you are abstracting?”   所谓“类型”是指所抽象的是什么? ---行成于思

Assembly language is a small abstraction of the underlying machine. Many so called imperative languages that followed (such as FORTRAN, BASIC, and C) were abstractions of assembly language. These languages are big improvements over assembly language, but their primary abstraction still requires you to think in terms of the structure of the computer rather than the structure of the problem you are trying to solve.

The alternative to modeling the machine(机器建模) is to model the problem you’re trying to solve. Each of these approaches may be a good solution to the particular class of problem they’re designed to solve, but when you step outside of that domain they become awkward. (不尽然,AI时代了)

OOP allows you to describe the problem in terms of the problem, rather than in terms of the computer where the solution will run. There’s still a connection back to the computer: Each object looks quite a bit like a little computer—it has a state, and it has operations that you can ask it to perform.


These characteristics represent a pure approach to object-oriented programming:

1.Everything is an object.

2.A program is a bunch of objects(程序是对象的集合) telling each other what to do by sending messages.

3.Each object has its own memory made up of other objects.

4.Every object has a type.

5.All objects of a particular type can receive the same messages.

1.2 An object has an interface (每个对象都有接口)

Since a class describes a set of objects that have identical characteristics (data elements) and behaviors (functionality), a class is really a data type because a floating point number, for example, also has a set of characteristics and behaviors.


The preceding diagram follows the format of the Unified Modeling Language (UML). Each class is represented by a box, with the type name in the top portion of the box, any data members that you care to describe in the middle portion of the box, and the methods (the functions that belong to this object, which receive any messages you send to that object) in the bottom portion of the box.

Light lt = new light();  
lt.on();

The interface determines the requests that you can make for a particular object. However, there must be code somewhere to satisfy that request. This, along with the hidden data, comprises the implementation.

Here, the name of the type/class is Light, the name of this particular Light object is lt, and the requests that you can make of a Light object are to turn it on, turn it off, make it brighter, or make it dimmer. You create a Light object by defining a reference for that object and calling new to request a new object of that type. To send a message to the object, you state the name of the object and connect it to the message request with a period (dot). From the standpoint of the user of a predefined class, that’s pretty much all there is to programming with objects.

1.3 An object provides services (每个对象都提供服务)

While you’re trying to develop or understand a program design, one of the best ways to think about objects is as "service providers." Your program itself will provide services to the user, and it will accomplish this by using the services offered by other objects. Your goal is to produce (or even better, locate in existing code libraries) a set of objects that provide the ideal services to solve your problem.

Thinking of an object as a service provider has an additional benefit: It helps to improve the cohesiveness of the object.

High cohesion is a fundamental quality of software design: It means that the various aspects of a software component (such as an object, although this could also apply to a method or a library of objects) "fit together" well.

1.4 The hidden implementation (被隐藏的具体实现)

The goal of the class creator is to build a class that exposes only what’s necessary to the client programmer and keeps everything else hidden.

Java uses three explicit keywords to set the boundaries in a class: public, private, and protected. These access specifiers determine who can use the definitions that follow. public means the following element is available to everyone. The private keyword, on the other hand, means that no one can access that element except you, the creator of the type, inside methods of that type. private is a brick wall between you and the client programmer. Someone who tries to access a private member will get a compile-time error. The protected keyword acts like private, with the exception that an inheriting class has access to protected members, but not private members.

Java also has a default access, which comes into play if you don’t use one of the aforementioned specifiers. This is usually called package access because classes can access the members of other classes in the same package (library component), but outside of the package those same members appear to be private.

1.5 Reusing the implementation (复用的具体实现)

Code reuse is one of the greatest advantages that object oriented programming languages provide. The simplest way to reuse a class is to just use an object of that class directly, but you can also place an object of that class inside a new class.

We call this creating a member object. Your new class can be made up of any number and type of other objects, in any combination that you need to achieve the functionality desired in your new class. Because you are composing a new class from existing classes,this concept is called composition (if the composition happens dynamically, it’s usually called aggregation). Composition is often referred to as a has-a relationship, as in A car has an engine.

1.6 Inheritance (继承)

It’s nicer if we can take the existing class, clone it, and then make additions and modifications to the clone. This is effectively what you get with inheritance, with the exception that if the original class (called the base class or superclass or parent class) is changed, the modified clone (called the derived class or inherited class or subclass or child class) also reflects those changes.

Although inheritance may sometimes imply (especially in Java, where the keyword for inheritance is extends) that you are going to add new methods to the interface, that’s not necessarily true. The second and more important way to differentiate your new class is to change the behavior of an existing base class method. This is referred to as overriding that method.

1.7 Interchangeable objects with polymorphism (伴随多态的可互换对象)

Object oriented languages use the concept of late binding. To perform late binding, Java uses a special bit of code in lieu of the absolute call. This code calculates the address of the method body, using information stored in the object.

In some languages you must explicitly state that you want a method to have the flexibility of late binding properties (C++ uses the virtual keyword to do this). In these languages, by default, methods are not dynamically bound. In Java, dynamic binding is the default behavior and you don’t need to remember to add any extra keywords in order to get polymorphism.

1.8 The singly rooted hierarchy (单根继承结构)

The name of this ultimate base class is simply Object. All objects in a singly rooted hierarchy have an interface in common, so they are all ultimately the same fundamental type.

All objects in a singly rooted hierarchy can be guaranteed to have certain functionality. You know you can perform certain basic operations on every object in your system. All objects can easily be created on the heap, and argument passing is greatly simplified.

A singly rooted hierarchy makes it much easier to implement a garbage collector, which is one of the fundamental improvements of Java over C++. This is especially important with system level operations, such as exception handling, and to allow greater flexibility in programming.

1.9 Containers (容器)

This new object, generally called a container(also called a collection, but the Java library uses that term in a different sense so this book will use container), will expand itself whenever necessary to accommodate everything you place inside it.

One of the big changes in Java SE5 is the addition of parameterized types, called generics in Java.You’ll recognize the use of generics by the angle brackets with types inside.

1.10 Object creation & lifetime (对象的创建和声明周期)

One critical issue when working with objects is the way they are created and destroyed. Each object requires resources, most notably memory, in order to exist. When an object is no longer needed it must be cleaned up so that these resources are released for reuse.

For maximum runtime speed, the storage and lifetime can be determined while the program is being written, by placing the objects on the stack (these are sometimes called automatic or scoped variables) or in the static storage area.

The second approach is to create objects dynamically in a pool of memory called the heap. Java uses dynamic memory allocation, exclusively. Every time you want to create an object, you use the new operator to build a dynamic instance of that object.

There’s another issue, however, and that’s the lifetime of an object. With languages that allow objects to be created on the stack, the compiler determines how long the object lasts and can automatically destroy it. However, if you create it on the heap the compiler has no knowledge of its lifetime.Java provides a feature called a garbage collector that automatically discovers when an object is no longer in use and destroys it. A garbage collector is much more convenient because it reduces the number of issues that you must track and the code you must write.

1.11 Exception handling: dealing with errors (异常处理:处理错误)

Exception handling wires error handling directly into the programming language and sometimes even the operating system.An exception is an object that is thrown from the site of the error and can be caught by an appropriate exception handler designed to handle that particular type of error.

1.12 Concurrent programming (并发编程)

A fundamental concept in computer programming is the idea of handling more than one task at a time. Many programming problems require that the program stop what it’s doing, deal with some other problem, and then return to the main process.

Sometimes, interrupts are necessary for handling time critical tasks, but there’s a large class of problems in which you’re simply trying to partition the problem into separately running pieces (tasks) so that the whole program can be more responsive. Within a program, these separately running pieces are called threads, and the general concept is called concurrency.

1.13 Java and the Internet

Although Java is very useful for solving traditional standalone programming problems, it is also important because it solves programming problems for the World Wide Web.

The primary idea of a client/server system is that you have a central repository of information some kind of data, usually in a database that you want to distribute on demand to some set of people or machines. You must ensure that one client’s new data doesn’t walk over another client’s new data, or that data isn’t lost in the process of adding it to the database (this is called transaction processing).

1.14 Summary

If you know that your needs will be very specialized for the foreseeable future and if you have specific constraints that may not be satisfied by Java, then you owe it to yourself to investigate the alternatives (in particular, I recommend looking at Python...)


JAVA圣经,第一章回头看会有一些不错的理论收获,至今看来仍是重要的指导思想。


chapter 0 Overwiew
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }