方法vs构造函数在Java [英] Methods vs Constructors in Java

查看:162
本文介绍了方法vs构造函数在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?

推荐答案

构造函数和方法之间的重要区别是构造函数创建和初始化尚不存在的对象,而方法执行操作对已存在的对象。

The important difference between constructors and methods is that constructors create and initialize objects that don't exist yet, 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.

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

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