0

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

user1766169
  • 1,932
  • 3
  • 22
  • 44
Applecow
  • 796
  • 3
  • 13
  • 35

3 Answers3

3

If you see the Integer class then it's

public final class Integer  extends Number implements Comparable<Integer>

you cannot extend the class as it's final

Mukesh Kumar
  • 317
  • 1
  • 5
  • 16
1

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
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
0

I agree with Mukesh Kumar.

And

Can you try following code ?

public class VInteger extends Number implements Comparable<Integer> {
Community
  • 1
  • 1
theMind
  • 194
  • 1
  • 10