我的问题是:如果我们想要使用一个对象,为什么我们必须将全局变量(成员、名称)传递给它。不是为所有对象声明了一个全局变量来访问它吗?
public class Family {
int members;
String names;
public Family(int members, string names) {
this.members = members;
this.names = names;
}
}发布于 2019-09-30 14:43:46
否则如何初始化对象中的变量呢?
让我试着这样解释你,假设你所要求的是可能的,那么,如果我们要创建100个不同的家庭对象,如果假设变量具有不同的数据,这怎么可能呢?因为更改全局字段会影响所有正确的对象。
因此,基本上在创建对象时,可以像在示例中那样使用构造函数初始化字段,也可以使用无参数构造函数,并在使用"Setters“创建对象后设置这些值。
了解更多关于初始化的信息。
希望这能有所帮助。
发布于 2019-09-30 17:33:45
上面提到的这段代码实际上是一个类定义。类只是一个模板,它包含与it.Now相关的成员变量和成员函数。 object 是类的一个实例,它已经为变量获取了一些值,这些变量通常是使用getter和setter来获取和设置的。respectively.Other操作可以由成员functions.Constructors执行,这些操作被用来初始化对象。
public Family(int members, string names) {
this.members = members;
this.names = names;
}是一个参数化构造函数,用于通过传递的参数初始化对象.This在创建一个类的1个以上的对象时显然很有用,因为每个对象都有与it.To相关的不同值更清楚:
public class Family {
int members;//member variable scope-class level
String names;//member variable scope-class level
public Family(int members, String names) {//int members,string names are parameters scope-constructor ,we can give any name to these two variables like int param_member,String param_names
this.members = members;//LHS specifies the variable- member of the class and RHS specifies variable passed as parameter
this.names = names; //LHS specifies the variable-names of the class and RHS specifies variable passed as parameter
}}
https://stackoverflow.com/questions/58162594
复制相似问题