我学习Java创建类,但遇到了奇怪的行为。
我想创建一个名为类My_class
具有调用的方法add
。该方法应该采取的成员My_class
并将其添加到另一构件My_class
中,括号中指定。
例如,运行以下命令:
My_class first = new My_class(2);
My_class second = new My_class(6);
My_class answer = first.add(second);
System.out.println(answer);
应打印:
8
下面是我使用的代码My_class
,但我一直运行到问题,关于如何My_class
与交易+
操作。我想,既然My_class
是继承int
,应该有没有问题,但很明显,我在这里失去了一些东西根本。
public class My_class {
/* Data members*/
private int integer;
/* Constructors */
public My_class(int i) {integer = i;}
/* Methods */
public My_class add(My_class new_integer) {
return integer + new_integer;
}
而不是预期的结果,我得到:
The operator + is undefined for the argument type(s) int, My_class
在此先感谢您的帮助!
由于错误消息说,你想添加的int
(integer
)和My_class
(new_integer
)。你不能做到这一点。
如果你想使用的integer
字段从new_integer
,你必须明确地访问它:
return integer + new_integer.integer;
// -------------------------^^^^^^^^
(可能是最好的重命名new_integer
参数的东西,并不意味着它是一个int
,因为它不是,它是一个实例My_class
。)
上述返回int
,因此该方法将是:
public int add(My_class new_integer) {
// ----^^^
return integer + new_integer.integer;
}
如果你想保持My_class
的返回值add
,你需要创建一个My_class
实例:
public My_class add(My_class new_integer) {
return new My_class(integer + new_integer.integer);
// ----^^^^^^^^^^^^^-----------------------------^
}
附注:我也强烈鼓励使用总this.
访问类的实例成员时,那么:
return this.integer + new_integer.integer;
// ----^^^^^
这是一个风格问题(Java编译器会推断出this.
在必要时),但恕我直言,它提高了清晰度,因为integer
其本身可以是一个局部变量,类名(虽然希望不是),静态成员,...
附注2:虽然你可以做任何你喜欢在自己的代码,铺天盖地的约定(也正式之一,PDF)是使用混合的情况下以大写字母开头的每个字,所以MyClass
不是My_class
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句