目录

  • 1 Java语言概述
    • 1.1 Java语言的特点
    • 1.2 Java虚拟机
    • 1.3 Java开发环境
    • 1.4 编译执行和解释执行
    • 1.5 第一个java程序1
    • 1.6 第一个java程序2
    • 1.7 第一个java程序3
    • 1.8 章节测验
  • 2 Java基础语法
    • 2.1 基本数据类型
    • 2.2 赋值语句
    • 2.3 表达式
    • 2.4 运算符
    • 2.5 类型转换
    • 2.6 章节测验
  • 3 类与对象
    • 3.1 面向对象的概念
    • 3.2 类和对象的概念
    • 3.3 构造方法
    • 3.4 章节测验
  • 4 继承与多态
    • 4.1 继承
    • 4.2 多态
    • 4.3 final关键字
    • 4.4 static关键字
    • 4.5 抽象类
    • 4.6 接口
    • 4.7 内部类
    • 4.8 章节测验
  • 5 数组和字符串
    • 5.1 数组
    • 5.2 字符串
    • 5.3 章节测验
  • 6 常用类与接口
    • 6.1 课件
    • 6.2 重要知识点
  • 7 异常处理
    • 7.1 课件
    • 7.2 重要知识点
  • 8 文件和流
    • 8.1 课件
    • 8.2 重要知识点
  • 9 Elements of Programming
    • 9.1 You First Program
      • 9.1.1 Exercise
      • 9.1.2 Program
    • 9.2 Built-in Types of Data
      • 9.2.1 Exercise
      • 9.2.2 Program
    • 9.3 Conditionals and Loops
      • 9.3.1 Exercise
      • 9.3.2 Program
    • 9.4 Arrays
      • 9.4.1 Exercise
      • 9.4.2 Program
    • 9.5 Input and Output
      • 9.5.1 Exercise
      • 9.5.2 Program
    • 9.6 Case Study: Random Web Surfer
  • 10 Functions
    • 10.1 Static Methods
      • 10.1.1 Exercise
      • 10.1.2 Program
    • 10.2 Libraries and Clients
      • 10.2.1 Exercise
      • 10.2.2 Program
    • 10.3 Recursion
      • 10.3.1 Exercise
      • 10.3.2 Program
    • 10.4 Case Study: Percolation
  • 11 Object-Oriented Programming
    • 11.1 Using Data Types
    • 11.2 Creating Data Types
    • 11.3 Designing Data Types
    • 11.4 Case Study: N-Body Simulation
  • 12 参考资料
    • 12.1 主要参考书
    • 12.2 慕课资源
Creating Data Types

In this section, we introduce the Java mechanism that enables us to create user-defined data types. We consider a range of examples, from charged particles and complex numbers to turtle graphics and stock accounts.

Basic elements of a data type.

 To illustrate the process, we define in Charge.java a data type for charged particles. Coulomb’s law tells us that the electric potential at a point (x,y) due to a given charged particle is V=kq/r, where q is the charge value, r is the distance from the point (x,y) to the charge, and k=8.99×109 is the electrostatic constant.

  • API. The application programming interface is the contract with all clients and, therefore, the starting point for any implementation.


  • Class. In Java, you implement a data type in a class. As usual, we put the code for a data type in a file with the same name as the class, followed by the .java extension.

  • Access modifiers. We designate every instance variable and method within a class as either public (this entity is accessible by clients) orprivate (this entity is not accessible by clients). The final modifier indicates that the value of the variable will not change once it is initialized—its access is read-only.

  • Instance variables. We declare instance variables to represent the data-type values in the same way as we declare local variables, except that these declarations appear as the first statements in the class, not inside main() or any other method. For Charge, we use threedouble variables—two to describe the charge’s position and one to describe the amount of charge.


  • Constructors. A constructor is a special method that creates an object and provides a reference to that object. Java automatically invokes a constructor when a client program uses the keyword new. Each time that a client invokes a constructor, Java automatically

      1. Allocates memory for the object

      2. Invokes the constructor code to initialize the instance variables

      3. Returns a reference to the newly created object

The constructor in Charge is typical: it initializes the instance variables with the values provided by the client as arguments.


  • Instance methods. To implement instance methods, we write code that is precisely like code for implementing static methods. The one critical distinction is that instance methods can perform operations on instance variables.


  • Variables within methods. The Java code we write to implement instance methods uses three kinds of variables. Parameter variables and local variables are familiar. Instance variables are completely different: they hold data-type values for objects in a class.

    Each object in the class has a value: the code in an instance method refers to the value for the object that was used to invoke the method. For example, when we write c1.potentialAt(x, y), the code in potentialAt() is referring to the instance variables for c1.


  • Test client. Each class can define its own main() method, which we reserve for unit testing. At a minimum, the test client should call every constructor and instance method in the class.


In summary, to define a data type in a Java class, you need instance variables, constructors, instance methods, and a test client.


Stopwatch.

 Stopwatch.java implements the following API:

It is a stripped-down version of an old-fashioned stopwatch. When you create one, it starts running, and you can ask it how long it has been running by invoking the method elapsedTime().


Histogram.

 Histogram.java is a data type to visualize data using a familiar plot known as a histogram. For simplicity, we assume that the data consists of a sequence of integer values between 0 and n−1. A histogram counts the number of times each value appears and plots a bar for each value (with height proportional to its frequency). The following API describes the operations:


Turtle graphics.

 Turtle.java is a mutable type for turtle graphics, in which we command a turtle to move a specified distance in a straight line, or rotate (counterclockwise) a specified number of degrees.

Here are a few example clients:

  • Regular n-gons. Ngon.java takes a command-line argument n and draws a regular n-gon using turtle graphics. By taking n to a sufficiently large value, we obtain a good approximation to a circle.

  • Recursive graphics. Koch.java takes a command-line argument n and draws a Koch curve of order n. A Koch curve of order order 0 is a line segment. To form a Koch curve of order n:


  • Draw a Koch curve of order n−1

  • Rotate 60° counterclockwise

  • Draw a Koch curve of order n−1

  • Rotate 120° clockwise

  • Draw a Koch curve of order n−1

  • Rotate 60° counterclockwise

  • Draw a Koch curve of order n−1


Below are the Koch curves of order 0, 1, 2, and 3.


  • Spira mirabilis. Spiral.java takes an integer n and a decay factor as command-line arguments, and instructs the turtle to alternately step and turn until it has wound around itself 10 times. This produces a geometric shape known as a logarithmic spiral, which arise frequently in nature. Three examples are depicted below: the chambers of a nautilus shell, the arms of a spiral galaxy, and the cloud formation in a tropical storm.




  • Brownian motion. DrunkenTurtle.java plots the path followed by a disoriented turtle, who alternates between moving forward and turning in a random direction. This process is known as Brownian motion. DrunkenTurtles.java plots many such turtles, all of whom wander around.


Complex numbers.

 A complex number is a number of the form x + iy, where x and y are real numbers and i is the square root of −1. The basic operations on complex numbers are to add and multiply them, as follows:

Complex.java is an immutable data type that implements the following API:

This data type introduces a few new features.

  • Accessing values of other objects of the same type. The instance methods plus() and times() each need to access values in two objects: the object passed as an argument and the object used to invoke the method. If we call the method with a.plus(b), we can access the instance variables of a using the names re and im, as usual. However, to access the instance variables of b, we use the codeb.re and b.im.

  • Creating and returning new objects. Observe the manner in which plus() and times() provide return values to clients: they need to return a Complex value, so they each compute the requisite real and imaginary parts, use them to create a new object, and then return a reference to that object.

  • Chaining method calls. Observe the manner in which main() chains two method calls into one compact expressionz.times(z).plus(z0), which corresponds to the mathematical expression z2 + z0.

  • Final instance variables. The two instance variables in Complex are final, meaning that their values are set for each Complex object when it is created and do not change during the lifetime of that object.


Mandelbrot set.

 The Mandelbrot set is a specific set of complex numbers with many fascinating properties. The algorithm for determining whether or not a complex number z0 is in the Mandelbrot set is simple: Consider the sequence of complex numbers z0,z1,z2,,zt,, wherezi+1=zi2+z0. For example, the following table shows the first few entries in the sequence corresponding to z0=1+i:

Now, if the sequence |zi| diverges to infinity, then z0 is not in the Mandelbrot set; if the sequence is bounded, then z0 is in the Mandelbrot set. For many points, the test is simple; for many other points, the test requires more computation, as indicated by the examples in the following table:

To visualize the Mandelbrot set, we define an evenly spaced n-by-n pixel grid within a specified square and draw a black pixel if the corresponding point is in the Mandelbrot set and a white pixel if it is not.

But how do we determine whether a complex number is in the Mandelbrot set? For each complex number, Mandelbrot.java computes up to 255 terms in its sequence. If the magnitude ever exceeds 2, then we can conclude that the complex number is not in the set (because it is known that the sequence will surely diverge). Otherwise, we conclude that the complex number is in the set (knowing that our conclusion might be wrong on occasion).

Commercial data processing.

 StockAccount.java implements a data type that might be used by a financial institution to keep track of customer information.