Java中构造函数的目的? [英] Purpose of a constructor in Java?

查看:25
本文介绍了Java中构造函数的目的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构造函数的目的是什么?我一直在学校学习 Java,在我看来,构造函数在我们迄今为止所做的事情中基本上是多余的.目的是否实现还有待观察,但到目前为止对我来说似乎毫无意义.比如下面两段代码有什么区别?

What is the purpose of a constructor? I've been learning Java in school and it seems to me like a constructor is largely redundant in things we've done thus far. It remains to be seen if a purpose comes about, but so far it seems meaningless to me. For example, what is the difference between the following two snippets of code?

public class Program {    
    public constructor () {
        function();
    }        
    private void function () {
        //do stuff
    }    
    public static void main(String[] args) { 
        constructor a = new constructor(); 
    }
}

这就是我们被教导如何处理作业的方式,但下面的内容不也一样吗?

This is how we were taught do to things for assignments, but wouldn't the below do the same deal?

public class Program {    
    public static void main(String[] args) {
        function();
    }        
    private void function() {
        //do stuff
    }
}

构造函数的目的让我无法理解,但话说回来,我们迄今为止所做的一切都非常简陋.

The purpose of a constructor escapes me, but then again everything we've done thus far has been extremely rudimentary.

推荐答案

构造函数用于初始化类的实例.您使用构造函数来创建新对象,通常使用指定初始状态或有关对象的其他重要信息的参数

Constructors are used to initialize the instances of your classes. You use a constructor to create new objects often with parameters specifying the initial state or other important information about the object

来自官方 Java 教程:

类包含构造函数,这些构造函数被调用以根据类蓝图创建对象.构造函数声明看起来像方法声明——除了它们使用类的名称并且没有返回类型.例如,Bicycle 有一个构造函数:

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}

要创建一个名为 myBike 的新 Bicycle 对象,new 操作符会调用一个构造函数:

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) 在内存中为对象创建空间并初始化其字段.

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

虽然 Bicycle 只有一个构造函数,但它可以有其他构造函数,包括无参数构造函数:

Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

公共自行车(){齿轮= 1;节奏 = 10;速度 = 0;}

public Bicycle() { gear = 1; cadence = 10; speed = 0; }

Bicycle yourBike = new Bicycle(); 调用无参数构造函数来创建一个名为 yourBike 的新 Bicycle 对象.

Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike.

这篇关于Java中构造函数的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆