0

getClass() in java is a method which returns runtime class of an object. For example:

String str = "something";

Then str.getClass() will return java.lang.String. That's okay. However, what does it mean when the getClass() called "dependently". I mean, in this case getClass() is called after the . operator. But in some cases, it can be called like getClass().getResourceAsStream(). I don't know what it is actually.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    The [`Object#getClass()`](https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/Object.html#getClass()) method returns a [`java.lang.Class`](https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/Class.html) instance, and the `java.lang.Class` class defines a [`Class#getResourceAsStream(String)`](https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/Class.html#getResourceAsStream(java.lang.String)) method. So, you get a class object and then call a method on that object immediately. This is known as "method chaining". – Slaw Jun 17 '22 at 03:58
  • And note that `str.getClass()` will return a `java.lang.Class extends java.lang.String>`. – Slaw Jun 17 '22 at 03:59
  • When any method returns a value of reference type, it can then be used immediately to call a method on that type, without having to use an intermediate variable. – user207421 Jun 17 '22 at 04:03
  • @Slaw Thanks. I understand now. One more question is can we instantiate a class object without using the getClass() method? – Nguyễn Tùng Dương Jun 17 '22 at 04:17
  • 1
    No, you cannot instantiate a `Class` object, as the class does not define a public constructor. A `Class` object is created by a `ClassLoader`, if and when needed. That said, in typical circumstances, there are two other ways to get a reference to a `Class` object other than the `Object#getClass()` method. One of those ways is via a class literal (e.g., `String.class`). That will only work if you know of the class at compile-time, however. The other way is to use one of the `Class#forName(...)` static methods (which can work without knowing the class name at compile-time). – Slaw Jun 17 '22 at 04:31
  • `getClass().getResourceAsStream()` is the same as `this.getClass().getResourceAsStream()`. – Mark Rotteveel Jun 17 '22 at 06:19

0 Answers0