java - difference between 2 types of downcasting -
public class { main() { // different implications of these 2 down casts superclass trefvar = new subclass(); // down cast example 1 subclass avar = (subclass) trefvar; // down cast example 2 ((subclass) trefvar).somemethodinsubclass(); } }
implications, wise, differences between example 1 cast, , example 2 cast?
there virtually no difference. first example creates new local variable, , second example doesn't. that's it.
to peek under hood bit , verify that, let's consider simple class, 2 methods you're doing in example:
public class downcasts { public int stringlength1(object o) { string s = (string) o; return s.length(); } public int stringlength2(object o) { return ((string) o).length(); } }
the bytecode these methods (which can see javap -c downcasts
) are:
public int stringlength1(java.lang.object); code: 0: aload_1 1: checkcast #2 // class java/lang/string 4: astore_2 5: aload_2 6: invokevirtual #3 // method java/lang/string.length:()i 9: ireturn public int stringlength2(java.lang.object); code: 0: aload_1 1: checkcast #2 // class java/lang/string 4: invokevirtual #3 // method java/lang/string.length:()i 7: ireturn
the first method these things:
string s = (string) o
:- loads
o
stack - checks it's string
- stores register 2
- loads
return s.length()
:- loads register 2 stack (that's 1 saved)
- invokes
string::length
(a virtual function) on it - returns result
the second method does:
return ((string) o).length()
:- loads
o
stack - checks it's string
- invokes
string::length
(a virtual function) on it - returns result
- loads
Comments
Post a Comment