object - How does getClass in Java work -
here javadoc says:
public final class <?> getclass()
returns runtime class of
object
. returnedclass
object object lockedstatic synchronized
methods of represented class.
the actual result typeclass<? extends |x|>
|x|
erasure of static type of expression ongetclass
called. example, no cast required in code fragment:number n = 0; class<? extends number> c = n.getclass();
returns:
class object represents runtime class of object.
now , understand native method , is implemented in platform-dependent code. return type of method.
public final class<?> getclass()
also , consider code:
class dog { @override public string tostring() { return "cat"; } } public class main { public static void main(string[] args) { dog d= new dog(); //class<dog> dd = new dog(); compile time error system.out.println(d.getclass()); } }
output:
class dog
so, query lies in :
- return type of method
- tostring method not called . similar post on topic : java. getclass() returns class, how come can string too?
- the commented code otherwise give compile time error.
the data each object contains reference object of class java.lang.class, , returned method getclass. there 1 java.lang.class object describing java.lang.class.
think of class object "blueprint" describing class objects being made. stands reason blueprints need blueprint of own (or else how engineers know how make blueprints).
these statements try illustrate this.
integer integer = 1; class<?> clazzinteger = integer.getclass(); system.out.println( "class of integer=" + clazzinteger ); class<?> clazzclazzinteger = clazzinteger.getclass(); system.out.println( "class of class integer's class=" + clazzclazzinteger ); string string = "x"; class<?> clazzstring = string.getclass(); system.out.println( "class of string=" + clazzstring ); class<?> clazzclazzstring = clazzstring.getclass(); system.out.println( "class of class string's class=" + clazzclazzstring );
output:
class of integer=class java.lang.integer class of class integer's class=class java.lang.class class of string=class java.lang.string class of class string's class=class java.lang.class
a class has name, described blueprint has name not confused blueprint itself. if class object appears in context, tostring() method called implicitly, , returns class' name. if you'd print nitty-gritty details of class (akin printing blueprint itself) you'd have write lot of code - @ javadoc java.lang.class: there's awful lot of information retrieved (as befits blueprint).
Comments
Post a Comment