Kalec
Kalec

Reputation: 2881

Having trouble with a small example from school

The example is from a course, it's for comparing two objects in java:

public class Complex {

    ...

    public boolean equals (Object obj) {
        if (obj instanceof Complex) {    // if obj is "Complex" (complex number) 
            Complex c =  (Complex) obj   // No idea
            return (real == c.real) && (imag == c.imag); 
            // I'm guessing real means [this].real
        }
        return false;
    }
}

So, my question is: "what does this: Complex c = (Complex) obj actually mean" ?

Also I've worked with python and c++, java is new for me.

Upvotes: 0

Views: 90

Answers (4)

Dan Dinu
Dan Dinu

Reputation: 33408

See my comments inline.

    public class Complex {

...

public boolean equals (Object obj) {
    if (obj instanceof Complex) {    // you first need to check whetever the obhect passed to the equal method is indeed of type "Complex" because i guess what you want here is to compare two Complex objects.
        Complex c =  (Complex) obj   // If the object is complex then you need to treat it as complex so cast it to Complex type in order to compare the "real" and "imag" values of the object.
        return (real == c.real) && (imag == c.imag); 
        // I'm guessing real means [this].real
        // yes, it does.
    }
    return false;
}

}

Read more about type casting at here

You can also check boxing and unboxing concept.

Hope this helps, Dan

Upvotes: 2

thar45
thar45

Reputation: 3560

  Complex c =  (Complex) obj  

Typecasting Complex is class casting the object obj type to Complex type

Could refer this link for reference for C++ reference to Java

Correct me if 'm wrong

Upvotes: 0

Sergii Zagriichuk
Sergii Zagriichuk

Reputation: 5399

It means casting input Object type to Complex type, after this line you can use all api from Complex class.

Upvotes: 1

Mr.Chowdary
Mr.Chowdary

Reputation: 3417

obj instanceof Complex  

It means obj may be the instance of Complex or its subclass..

Complex c =  (Complex) obj  

Means you are typecasting it to Complex class object if it is of subclass object

Upvotes: 2

Related Questions