介绍 ( Introduction )

Before you read this step-by-step guide you might want to cast your eye over the introduction to object-oriented programming. The Java code contained in the following steps matches the example of a Book object used in the theory of that article.​

在阅读本分步指南之前,您可能需要对面向对象编程的介绍有所了解 。 以下步骤中包含的Java代码与该文章的理论中使用的Book对象的示例相匹配。

By the end of this guide you will have learned how to:

到本指南结束时,您将学习如何:

  • design an object设计一个对象
  • store data in an object将数据存储在对象中
  • manipulate data in an object处理对象中的数据
  • create a new instance of an object创建一个对象的新实例

类文件 ( The Class File )

If you're new to objects you will most likely be used to created Java programs using only one file – a Java main class file. It's the class that has the main method defined for the starting point of a Java program.

如果您不熟悉对象,则很可能会习惯于仅使用一个文件(Java主类文件)来创建Java程序。 该类具有为Java程序的起点定义的main方法。

The class definition in the next step needs to be saved in a separate file. It follows the same naming guidelines as you have been using for the main class file (i.e., the name of the file must match the name of the class with the filename extension of .java). For example, as we are making a Book class the following class declaration should be saved in a file called "Book.java".

下一步中的类定义需要保存在单独的文件中。 它遵循与主类文件相同的命名准则(即,文件名必须与文件名扩展名为.java的类名匹配)。 例如,当我们制作Book类时,以下类声明应保存在名为“ Book.java”的文件中。

班级宣言 ( The Class Declaration )

The data an object holds and how it manipulates that data is specified through the creation of a class. For example, below is a very basic definition of a class for a Book object:

通过创建类来指定对象保存的数据以及如何处理该数据。 例如,以下是Book对象的类的非常基本的定义:

public class Book { }

It's worth taking a moment to break down the above class declaration. The first line contains the two Java keywords "public" and "class":

值得花点时间来分解上面的类声明。 第一行包含两个Java关键字“ public”和“ class”:

  • The public keyword is known as an access modifier. It controls what parts of your Java program can access your class. In fact, for top-level classes (i.e., classes not contained within another class), like our book object, they have to be public accessible.public关键字被称为访问修饰符。 它控制Java程序的哪些部分可以访问您的类。 实际上,对于顶级类(即,其他类中未包含的类),例如我们的书本对象,它们必须是公共可访问的。
  • The class keyword is used to declare that everything within the curly brackets is part of our class definition. It's also followed directly by the name of the class.class关键字用于声明大括号内的所有内容都是我们类定义的一部分。 它也直接跟在类的名称之后。

领域 ( Fields )

Fields are used to store the data for the object and combined they make up the state of an object. As we're making a Book object it would make sense for it to hold data about the book's title, author, and publisher:

字段用于存储对象的数据,并结合起来构成对象的状态。 当我们制作Book对象时,有意义的是保存有关书名,作者和出版商的数据:

public class Book {    //fields    private String title;    private String author;    private String publisher; }

Fields are just normal variables with one important restriction – they must use the access modifier "private". The private keyword means that theses variables can only be accessed from inside the class that defines them.

字段只是具有一个重要限制的普通变量–它们必须使用访问修饰符“ private”。 private关键字意味着只能从定义它们的类内部访问这些变量。

Note: this restriction is not enforced by the Java compiler. You could make a public variable in your class definition and the Java language won't complain about it. However, you will be breaking one of the fundamental principles of object-oriented programming – data encapsulation. The state of your objects must only be accessed through their behaviors. Or to put it in practical terms, your class fields must only be accessed through your class methods. It's up to you to enforce data encapsulation on the objects you create.

注意: Java编译器没有强制执行此限制。 您可以在类定义中创建一个公共变量,而Java语言不会抱怨它。 但是,您将打破面向对象编程的基本原理之一-数据封装 。 您只能通过对象的行为来访问它们的状态。 换句话说,您只能通过类方法访问您的类字段。 由您决定对创建的对象实施数据封装。

构造方法 ( The Constructor Method )

Most classes have a constructor method. It's the method that gets called when the object is first created and can be used to set up its initial state:

大多数类都有构造函数方法。 这是在首次创建对象时调用的方法,可用于设置其初始状态:

 public class Book {    //fields    private String title;    private String author;    private String publisher;    //constructor method    public Book(String bookTitle, String authorName, String publisherName)    {      //populate the fields      title = bookTitle;      author = authorName;      publisher = publisherName;    } }

The constructor method uses the same name as the class (i.e., Book) and needs to be publicly accessible. It takes the values of the variables that are passed into it and sets the values of the class fields; thereby setting the object to it's initial state.

构造方法使用与类(即Book)相同的名称,并且需要可公开访问。 它获取传递给它的变量的值并设置类字段的值。 从而将对象设置为其初始状态。

新增方法 ( Adding Methods )

Behaviors are the actions an object can perform and are written as methods. At the moment we have a class that can be initialized but doesn't do much else. Let's add a method called "displayBookData" that will display the current data held in the object:

行为是对象可以执行的动作,并被编写为方法。 目前,我们有一个可以初始化但没有做很多其他事情的类。 让我们添加一个名为“ displayBookData”的方法,该方法将显示对象中保存的当前数据:

 public class Book {    //fields    private String title;    private String author;    private String publisher;    //constructor method    public Book(String bookTitle, String authorName, String publisherName)    {      //populate the fields      title = bookTitle;      author = authorName;      publisher = publisherName;    }    public void displayBookData()    {      System.out.println("Title: " + title);      System.out.println("Author: " + author);      System.out.println("Publisher: " + publisher);    } }

All the displayBookData method does is print out each of the class fields to the screen.

displayBookData方法所做的全部工作是将每个类字段打印到屏幕上。

We could add as many methods and fields as we desire but for now let's consider the Book class as complete. It has three fields to hold data about a book, it can be initialized and it can display the data it contains.

我们可以根据需要添加任意数量的方法和字段,但现在让我们考虑Book类是否完整。 它具有三个字段来保存有关书籍的数据,可以对其进行初始化并显示其中包含的数据。

创建对象的实例 ( Creating an Instance of an Object )

To create an instance of the Book object we need a place to create it from. Make a new Java main class as shown below (save it as BookTracker.java in the same directory as your Book.java file):

要创建Book对象的实例,我们需要一个地方来创建它。 制作一个新的Java主类,如下所示(将其保存为BookTracker.java与Book.java文件位于同一目录中):

 public class BookTracker {    public static void main(String[] args) {    } }

To create an instance of the Book object we use the "new" keyword as follows:

要创建Book对象的实例,我们使用“ new”关键字,如下所示:

 public class BookTracker {    public static void main(String[] args) {      Book firstBook = new Book("Horton Hears A Who!","Dr. Seuss","Random House");    } }

On the left hand side of the equals sign is the object declaration. It's saying I want to make a Book object and call it "firstBook". On the right hand side of the equals sign is the creation of a new instance of a Book object. What it does is go to the Book class definition and run the code inside the constructor method. So, the new instance of the Book object will be created with the title, author and publisher fields set to "Horton Hears A Who!", "Dr Suess" and "Random House" respectively. Finally, the equals sign sets our new firstBook object to be the new instance of the Book class.

等号的左侧是对象声明。 就是说我要创建一个Book对象并将其称为“ firstBook”。 等号的右侧是Book对象的新实例的创建。 它要做的是转到Book类定义,然后在构造方法中运行代码。 因此,将创建书名对象的新实例,并将标题,作者和发布者字段分别设置为“霍顿听见某人!”,“苏斯博士”和“随机屋”。 最后,等号将我们的新firstBook对象设置为Book类的新实例。

Now let's display the data in firstBook to prove that we really did create a new Book object. All we have to do is call the object's displayBookData method:

现在,让我们在firstBook中显示数据以证明我们确实创建了一个新的Book对象。 我们要做的就是调用对象的displayBookData方法:

 public class BookTracker {    public static void main(String[] args) {      Book firstBook = new Book("Horton Hears A Who!","Dr. Seuss","Random House");      firstBook.displayBookData();    } }

The result is:Title: Horton Hears A Who!Author: Dr. SeussPublisher: Random House

结果是:标题:霍顿听到了谁!作者:苏斯博士出版者:兰登书屋

多个物件 ( Multiple Objects )

Now we can begin to see the power of objects. I could extend the program:

现在我们可以开始看到物体的力量了。 我可以扩展程序:

 public class BookTracker {    public static void main(String[] args) {      Book firstBook = new Book("Horton Hears A Who!","Dr. Seuss","Random House");      Book secondBook = new Book("The Cat In The Hat","Dr. Seuss","Random House");      Book anotherBook = new Book("The Maltese Falcon","Dashiell Hammett","Orion");      firstBook.displayBookData();      anotherBook.displayBookData();      secondBook.displayBookData();    } }

From writing one class definition we now have the ability to create as many Book objects as we please!

通过编写一个类定义,我们现在可以根据需要创建尽可能多的Book对象!

翻译自: https://www.thoughtco.com/designing-and-creating-objects-2034342

用JavaScript设计和创建对象相关推荐

  1. 《JavaScript设计与开发新思维》——1.7 JavaScript编程目标

    本节书摘来自异步社区<JavaScript设计与开发新思维>一书中的第1章,第1.7节,作者:[美]Larry Ullman著,更多章节内容可以访问云栖社区"异步社区" ...

  2. Javascript第六章JavaScript中构造器创建对象第二课

    Javascript第六章JavaScript用new创建对象第一课 https://blog.csdn.net/qq_30225725/article/details/89304586 Javasc ...

  3. Javascript第六章JavaScript用new创建对象第一课

    Javascript第六章JavaScript用new创建对象第一课 https://blog.csdn.net/qq_30225725/article/details/89304586 Javasc ...

  4. Javascript三种创建对象的方法,new关键字,for...in 遍历对象

    在Javascript中,对象是一组无序的相关属性和方法的集合,例如:字符串.数值.数组.函数等. 对象是有属性和方法组成 属性:事物的特征 方法:事物的行为 字面量创建对象:{ } 里面包含了表达这 ...

  5. JavaScript对象与创建对象的方式

    引言 创建自定义对象最简单的方式就是创建一个Object的实例,然后再为它添加属性和方法,早期的开发人员经常使用这种模式来创建对象,后来对象字面量的方法成了创建对象的首选模式.虽然object构造函数 ...

  6. 如何使用 CSS flex box 和 Javascript 设计棋盘

    在这篇文章中,我将展示如何使用 css 和一些 JavaScript 来设计棋盘. 为此,你需要对 CSS Flex-box 和 nth-child() 属性有基本的了解. 所以让我们开始吧..... ...

  7. JavaScript 对象初探--创建对象

    目录 JavaScript对象概念 JavaScript类型 一.js中的对象 二.自定义对象 属性和方法 创建对象方式 一.对象字面量 二.内置构造函数 三.工厂模式 四.自定义构造函数的方法 五. ...

  8. 教你用 JavaScript 设计一个 Neumorphism 风格的数字时钟 (代码详解)

    时钟是我们用来测量时间的装置.如果使用得当,时钟对于任何 UI 都是有用的元素.时钟可用于以时间为主要关注点的网站,例如一些预订网站或一些显示火车.公共汽车.航班等到达时间的应用程序.时钟基本上有两种 ...

  9. JavaScript简餐——创建对象的三种模式

    文章目录 前言 一.工厂模式 二.构造函数模式 三.原型模式 总结 前言 写本<JavaScript简餐>系列文章的目的是记录在阅读学习<JavaScript高级程序设计(第4版)& ...

最新文章

  1. 手机蓝牙如何减少延时_如何使用车载蓝牙播放手机音乐的方法
  2. python算程序员吗_我算是优秀的程序员吗?
  3. CLR via C#学习笔记-第十三章-定义接口、继承接口
  4. python 关闭窗口事件_关于python:如何在Tkinter中处理窗口关闭事件?
  5. linux 常用工具
  6. Python: 装饰器的小例子
  7. Eclipse下的java工程目录问题和路径问题理解
  8. java学习之操作符
  9. 再谈 MySQL 备份
  10. 生产者消费者之爸爸妈妈儿子女儿苹果橘子编程实现
  11. 如何快速删除 Word 文档中的分节符
  12. mysql+一直running_mysql 事务一直running问题排查
  13. 一根均线选股法_一根均线选股法视频教程
  14. 苹果电脑破音的解决办法
  15. Word2vec 计算两个文本之间相似度
  16. EVE-NG模拟器社区版网络模拟环境搭建教程
  17. javascript中call的用法总结
  18. GRIB2 资料处理
  19. 攻防世界--进阶区--forgot
  20. 谷歌地图升级后,地图运行一会儿就卡住的ANR分析及解决方法

热门文章

  1. matlab仿真需要硬件,用Matlab/Simulink实现简单的硬件在环路仿真
  2. A - Even But Not Even
  3. JEPLUS之如何快速复制表——JEPLUS软甲快速开发平台
  4. MySQL 中的系统库之information_schema
  5. 常用计算机技能有哪些方面,办公室的word常用技巧有哪些,这些计算机技能只为让你事半功倍...
  6. DOM中NodeListNamedNodeMapHTMLCollection简介
  7. 计算机科学与工程考博题目,华南理工大学计算机科学与工程学院2016考博复试及录取安排...
  8. 网页Web上调用本地应用程序(.exe)
  9. 淘宝U站引流方法 教你淘宝U站推广流量如何自然来!
  10. 多线程与并发线程:创建一个容量为 100 升的水池,在水池设置 3 个出水口