Java OCA OCP Practice Question 2325

Question

Select the correct options.

class MyClass { //from   w  ww. j  a v a2 s  . c o m
    String name; 
    MyClass(String name) {this.name = name;} 
    public String toString() {return name;} 
    public boolean equals(Object obj) { 
        return (obj.toString().equals(name)); 
    } 
} 

  
  • a Class MyClass overrides method toString() correctly.
  • b Class MyClass overrides method equals() correctly.
  • c Class MyClass fails to compile.
  • d Class MyClass throws an exception at runtime.
  • e None of the above.


a

Note

Class MyClass overrides method toString() correctly, but not method equals().

According to the contract of method equals(), for any non-null reference values x and y, x.

equals(y) should return true if and only if y.

equals(x) returns true-this rule states that two objects should be comparable to each other in the same way.

Class MyClass doesn't follow this rule.


class TestMyClass { 
    public static void main(String args[]) { 
        MyClass color = new MyClass("red"); 
        String string = "red"; 

        System.out.println(color.equals(string));   // prints true 
        System.out.println(string.equals(color));   // prints false 
    } /*from   ww  w  .j  ava 2s .  c  o  m*/
} 



PreviousNext

Related