Java + operator behavior not inherited as expected

Jayden.Cameron :

I am learning to create classes in Java, but ran into strange behavior.

I want to create a class called My_class that has a method called add. The method should take a member of My_class and add it to another member of My_class specified in the parentheses.

E.g., running this:

My_class first = new My_class(2);
My_class second = new My_class(6);
My_class answer = first.add(second);
System.out.println(answer);

Should print:

8

Here is the code I am using for My_class, but I keep running into problems regarding how My_class deals with the + operator. I thought that since My_class is inheriting from int, that there should be no problem, but clearly I am missing something fundamental here.

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;
    }

Instead of the expected result I get:

The operator + is undefined for the argument type(s) int, My_class

Thanks in advance for any help!

T.J. Crowder :

As the error message says, you're trying to add an int (integer) and My_class (new_integer). You can't do that.

If you want to use the integer field from new_integer, you have to access it explicitly:

return integer + new_integer.integer;
// -------------------------^^^^^^^^

(Probably best to rename the new_integer parameter to something that doesn't imply that it's an int, since it isn't, it's an instance of My_class.)

The above returns int, so the method would be:

public int add(My_class new_integer) {
// ----^^^
    return integer + new_integer.integer;
}

If you want to keep the My_class return value of add, you need to create a My_class instance:

public My_class add(My_class new_integer) {
    return new My_class(integer + new_integer.integer);
    // ----^^^^^^^^^^^^^-----------------------------^
}

Side note: I also strongly encourage always using this. when accessing instance members of a class, so:

return this.integer + new_integer.integer;
// ----^^^^^

It's a matter of style (the Java compiler will infer this. where necessary), but IMHO it improves clarity, since integer on its own can be a local variable, a class name (though hopefully not), a static member, ...


Side note 2: Although you can do whatever you like in your own code, the overwhelming convention (also the official one, PDF) is to use mixed case with a capital letter starting each word, so MyClass rather than My_class.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328544&siteId=1