我确信这很简单。我有一个名为vInteger
的java类,它扩展了类Integer
(仅包含int
值,构造函数,getter)并实现了类Comparing
。那个有一个抽象方法compare(Comparing obj);
,我在类vInteger
中实现了它。但是,我无法从Integer
类调用getter来获取int
值。
这里有什么问题? :)
由于
答案 0 :(得分:3)
如果你看到Integer类那么它就是
public final class Integer extends Number implements Comparable<Integer>
你不能扩展课程,因为它是最后的
答案 1 :(得分:1)
我假设您指的是自定义Integer
课程(不是一个好主意,BTW,因为它会隐藏java.lang.Integer
,因此重命名它会更安全。)< / p>
现在,您有一个类似于此的类(基于您的描述):
public class vInteger extends Integer implements Comparing
{
...
public int compare(Comparing obj)
{
// here you can access this.getIntValue() (the getter of your Integer class)
// however, obj.getIntValue() wouldn't work, since `obj` can be of any
// class that implements `Comparing`. It doesn't have to be a sub-class of
// your Integer class. In order to access the int value of `obj`, you must
// first test if it's actually an Integer and if so, cast it to Integer
if (obj instanceof Integer) {
Integer oint = (Integer) obj;
// now you can do something with oint.getIntValue()
}
}
...
}
P.S。,更好的解决方案是使用通用比较接口:
public interface Comparing<T>
{
public int compare (T obj);
}
public class vInteger extends Integer implements Comparing<vInteger>
{
public int compare (vInteger obj)
{
// now you can access obj.getIntValue() without any casting
}
}
答案 2 :(得分:0)
我同意Mukesh Kumar。
和
您可以尝试使用代码吗?
public class VInteger extends Number implements Comparable<Integer> {