I am sure that this is an easy one. I have a java class called vInteger
, which extends the class Integer
(containing only int
value, constructor, getter) and implements class Comparing
. That one has an abstract method compare(Comparing obj);
and I implemented it in the class vInteger
. However, I can't call the getter from the Integer
class to get the int
value.
What is the problem here? :)
Thanks
I'm assuming you are referring to a custom Integer
class (not a great idea, BTW, since it will hide java.lang.Integer
, so it would be safer to rename it).
Now, you have a class that looks something like this (based on your description) :
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., a better solution is to use a generic Comparing interface :
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
}
}