无法在java中引用类

时间:2013-04-01 09:56:18

标签: java reference

class MyClass {
   int value;
}
public MyClass test(){
   MyClass mc;
   myMethod(mc, 100);
   if (mc!=null) {
      mc = mc.value;
      return mc;
   }
   return mc;
}
public int myMethod(MyClass mc, int a) {
   mc.value = a + 10;
   return mc;
}

我想把mc作为参考。如果objective-c与此类似:

public MyClass test(){
   MyClass *mc;
   myMethod(&mc, 100);

}

请帮帮我。任何答案都很感激。先谢谢你。

1 个答案:

答案 0 :(得分:1)

在java中,我们使用引用变量而不是指针。请参阅thisthis

class MyClass 
{
   int value;

/*All methods have to belong to a class*/

public MyClass test()
{
 /*MyClass mc; you don't need to pass this to assign value the value will be 
 assigned to the data members of the object(reference variable) which calls the
 function*/       

MyClass mc = myMethod(100);
return mc;
}

public MyClass myMethod(int a) 
{
   value = a + 10;
   return this; //This 'this' will return the current object
}
}