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

查看:231
本文介绍了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 ,构造函数由新运算符调用:

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

自行车myBike =新自​​行车(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:

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

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

自行车yourBike = new Bicycle(); 调用无参构造函数创建新的自行车对象称为yourBike。

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

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

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