[英]How does a method know which object to work on?
我不确定我的措辞是否正确,但我对方法如何判断它正在处理哪个对象感到困惑。 或者改写这个的另一种方式是你如何指定一个方法来处理某个对象?
例如,如果我创建了两个使用某种数组的对象。 假设 obj1 和 obj2。 如果我然后实现某种 add() 方法,它将向数组添加一些值。 如何区分 obj1.add(E value) 与 obj2.add(E value)。
我试过创建一个数组,但问题是 obj1.add() 和 obj2.add() 会编辑同一个数组,我希望它们分开工作。 在构造函数中,它给数组一个大小。
class Example{
int arr[];
Example(int a) {
int size = a;
arr = new int[a];
}
add(int value) {
// adds some value to the array
}
public static void main(String[] args) {
Example obj1 = new Example(5);
Example obj2 = new Example(10);
obj1.add(1);
obj2.add(2);
}
}
是否可以创建可以在自己的数组上工作的不同对象? 我非常困惑,因为 add 总是会修改 arr 并且只有一个数组。
所以,这是一个真正的初学者问题,但我会尽可能简单地解释它,因为当你开始时可能很难理解。
当你做
Example obj1 = new Example(5);
Example obj2 = new Example(10);
您正在 PC 的 RAM 中制作两个对象。
它们每个都有一个单独的内存地址,并根据需要占用尽可能多的空间。
您可以将 RAM 中的对象视为街道上的房屋。
Example Benny = new Example(5);
Example Jacob = new Example(10);
这条街现在有两间房子。 本尼和雅各布。
本尼的门牌号是 105
雅各布的门牌号是 42
他们的房子建造的完全一样。 唯一不同的是,Benny 可以接待 5 位客人,而 Jacob 可以接受 10 位客人。
当出租车过来添加客人时,他收到命令,将客人添加到 105 号街道。出租车开到 105 号街道,忽略任何不是 105 号的房屋,并将客人添加到该房屋中。
然后他返回调度并得到命令,将客人添加到 42 号街。然后他开车到 42 号街,将客人添加到那所房子。
由于地址不同,永远不会混淆哪些房子的客人被添加到哪个房子。 在此设置中,房屋不共享宾客空间。
我在下面添加了一个图表,以表明它们有不同的列表和不同的流程。
我希望这可以帮助您了解它的工作原理。
我想这很容易做到。 您可以在两个不同的对象中维护数组,如下所示:
class Example{
int arr[];
Example(int a)
{
int size = a;
this.arr= new int[a];
}
void add(int value)
{
// adds some value to the array
//your logic to insert values in the array
}
public static void main(String args[])
{
Example obj1 = new Example(5);
Example obj2 = new Example(10);
obj1.add(1);
obj2.add(2);
obj1.add(3);
obj2.add(4);
for(int i=0;i<obj1.arr.length;i++){ //obj1.arr is used to access the array of that object
System.out.println(obj1.arr[i]); //just for printing purpose
}
for(int j=0;j<obj2.arr.length;j++){
System.out.println(obj2.arr[j]); //just for printing purpose
}
}
}
在上面的代码中,您可以将this关键字与数组(this.arr)一起使用,以不同的方式维护不同对象中的数组。
希望这对你有帮助..
`公共类示例{ int arr[]; int currentElementsInArray=0;//这是当前数组中的元素个数
Example(int a) {
int size = a;
arr = new int[a];
}
public void add(int value) {
// adds some value to the array
this.arr[this.currentElementsInArray++]= value; /*this will add the incoming element to the next
vacant position of the array*/
}
public static void main(String[] args) {
Example obj1 = new Example(5);
Example obj2 = new Example(10);
obj1.add(1);
obj1.add(1);
obj1.add(5);
obj2.add(2);
obj2.add(4);
obj2.add(22);
//prints the elements in the first array
for(int i=0 ; i < obj1.currentElementsInArray ; i++){
System.out.println(obj1.arr[i]);
}
//prints the elements in the second array
for(int j=0 ; j < obj2.currentElementsInArray ; j++){
System.out.println(obj2.arr[j]);
}
}
}`
运行这个。 将为两个对象分别创建两个数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.