Java构造函数重载 [英] Java Constructor Overloading

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

问题描述

我是Java的新手,我无法理解构造函数的问题,
我看了很多教程,但我很难理解为什么我们使用构造函数,反正我的具体问题:

I'm new with Java and I'm having trouble understanding the constructor issue, I have looked at many tutorials and still I'm having difficult to understand why we use constructors, anyway, my specific question is :

如果我错了,更正我,如果我想在我的类中添加多个构造函数,我会写第一个,第二个将 int type(在括号内)。

Correct me if I'm wrong, if i want to add in my class more than one constructor, I'll write the first one and the second will be int type (inside the brackets).


  1. is it because the constructors have to be with the same name as the class and we need to distinguish between them ?

如果我想添加第三个构造函数,该怎么办?是否也可以 int 类型?

what if I want to add a third constructor ? Can it also be int type ?


推荐答案


a)构造函数必须与
类具有相同的名称,我们需要区分它们?

a) is it because the constructors have to be with the same name as the class and we need to distinguish between them ?

没有任何返回类型的类的名称,为了区分它们,可以有不同的参数。

Yes constructors are always the name of the class without any return type, and in order to distinguish between them, you can have different parameters.


b)如果我想添加第三个构造函数怎么办?它也可以是int类型

b) what if i want to add a third constructor ? it can be also int type ?

是的,您可以添加任何否。的重载构造函数,但那些都应该是不同的。和/或参数的类型。

Yes, you can add any no. of overloaded constructors but those all should be different in no. and/or type of parameters.

像: -

public User() // default constructor
{
}

public User(int age) // overloaded constructor with int
{
}

public User(String name) // // overloaded constructor with String
{
}

public User(String name, int age) // // overloaded constructor with String and int
{
}

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

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