object - How does getClass in Java work -


here javadoc says:

public final class <?> getclass() 

returns runtime class of object. returned class object object locked static synchronized methods of represented class.
the actual result type class<? extends |x|> |x| erasure of static type of expression on getclass 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 :

  1. return type of method
  2. tostring method not called . similar post on topic : java. getclass() returns class, how come can string too?
  3. 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

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -