+ 2
Can we override method(int) as method(Integer) like in the below example?
public class MainClass { public static void main(String[] args) { Integer i1 = 127; Integer i2 = 127; System.out.println(i1 == i2); Integer i3 = 128; Integer i4 = 128; System.out.println(i3 == i4); } }
2 odpowiedzi
+ 3
Hi Ankit, int is a primitive and Integer is an object.
If you instantiate an Integer object you should use this sintax:
Integer x=new Integer(1);
from java 1.5 there is a unboxing functionality that instantiate automatically the object:
Integer x=1;
Now the question:
Integer a=1;
Integer b=1;
(a==b) -> false!
Because a and b are two different objects!
(a.equals(b)) -> true!
Because if you should compare two objects you must use a specific implementation - "equals" that in this case would do a simple comparison == between the two int values.
You could use this rule in more complex objects.. Try to create your own Integer class where implementing the equals method (for an hint take a look at java code).
+ 1
No. It gives compile time error. Compiler treats int and Integer as two different types while overriding. Auto-boxing doesn’t happen here.