Java 中的方法与构造函数 [英] Methods vs Constructors in Java

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

问题描述

我刚刚开始使用 Java 编程.在谈论方法和构造函数时,我们使用的文本是缺乏的.我不确定方法或构造函数到底是什么,以及是什么使每个方法或构造函数独一无二.有人可以帮我定义它们并区分两者吗?

I have just started programming with Java. The text we use is lacking when talking about methods and constructors. I'm not sure what a method or a constructor is exactly and what makes each unique. Can someone please help me define them and differentiate between the two?

推荐答案

构造函数和方法之间的重要区别在于,构造函数初始化使用 new 操作符创建的对象,而方法执行操作已经存在的对象.

The important difference between constructors and methods is that constructors initialize objects that are being created with the new operator, while methods perform operations on objects that already exist.

不能直接调用构造函数;当 new 关键字创建一个对象时,它们会被隐式调用.可以直接在已经用 new 创建的对象上调用方法.

Constructors can't be called directly; they are called implicitly when the new keyword creates an object. Methods can be called directly on an object that has already been created with new.

构造函数和方法的定义在代码中看起来很相似.它们可以接受参数,可以具有修饰符(例如 public),并且可以在大括号中包含方法主体.

The definitions of constructors and methods look similar in code. They can take parameters, they can have modifiers (e.g. public), and they have method bodies in braces.

构造函数必须与类名同名.它们不能返回任何东西,即使是 void(对象本身就是隐式返回).

Constructors must be named with the same name as the class name. They can't return anything, even void (the object itself is the implicit return).

必须声明方法以返回某些内容,尽管它可以是 void.

Methods must be declared to return something, although it can be void.

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

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