0

Considering the following code:

@override
public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return Double.compare(employee.salary, salary) == 0 && id == employee.id && name.equals(employee.name) && hireDay.equals(employee.hireDay);
    }

since java is only "Call by Value", the method call is equivalent to:

Object o = x;

which is legal to assign a subclass var to a superclass type.

Now, as far as I learned, down-casting without using "instanceOf" operator throws "ClassCastException" at Run-Time. Why everything Works fine in this Scenario?

my second question is: what does instanceof operator do exactly and how JVM handles this operator. Why the Run-Time Environment does not know to the class hierarchy and It knows after instanceof operator?

if(o instanceof Employee)
   Employee em = (Employee) o;
   

The "instanceof" is an expression to boolean. What difference it makes if we evaluate the condition to true?

Employee em;
if(true)
   em = (Employee) o;

I have tried many forms of Type-Casting and all require to check type at Run-Time.

I appreciate your response in advance.

mas
  • 1
  • 1
    "Why everything Works fine in this Scenario?" <- Because there is an if check if the passed object is of the same class as the object the method belongs to, which I presume to be Employee or a subclass. So if the passed object can't be cast to Employee it would never reach the casting point of that code. – OH GOD SPIDERS Aug 31 '21 at 10:23
  • *"down-casting without using `instanceOf` operator throws `ClassCastException` at Run-Time."* no. It *could* throw if the object can't be cast to a certain type. – Federico klez Culloca Aug 31 '21 at 10:28
  • 1
    *"down-casting without using "instanceOf" operator throws "ClassCastException""* — Not always. There are other methods to check this, for instance `getClass()`. Also, if you, as the author, *know* that you pass only objects of a certain type to a method, then it's safe to cast without check. – MC Emperor Aug 31 '21 at 10:29
  • `Object o = x;` won't change the fact that `x` is an instance of `Employee`, and so will `o`. – sp00m Aug 31 '21 at 10:29
  • Earlier explanations here: [instanceof vs getClass](https://stackoverflow.com/questions/4989818/instanceof-vs-getclass) or [any reason to prefer getclass over instanceof](https://stackoverflow.com/questions/596462/any-reason-to-prefer-getclass-over-instanceof-when-generating-equals) – Nowhere Man Aug 31 '21 at 10:32

0 Answers0