Reputation: 1
for example in Scanner we have obj.next()
but we can call another method after next()
obj.next().charAt(0)
how can I make similar thing for example
obj.getName().toLowerCase()
Upvotes: 0
Views: 48
Reputation: 5794
What you have observed – with examples like obj.getName().toLowerCase()
– is that when the return type of a method call is itself some other object, then you can immediately call a new method on that newly returned object.
Here's another example: String s = String.class.getName().toLowerCase();
. This example could be rewritten like so:
Class<String> stringClass = String.class;
String name = stringClass.getName();
String s = name.toLowerCase();
Both of the one-line and multi-line version of this code result in a String object, referenced by s
, which contains the value "java.lang.string
".
Note that chaining method calls together is not possible if the return type isn't an object, such as an integer
value. For example, here's a method call that results in a primitive long
value, which isn't an object, so you can't call any methods on that result – that is, something like millis.hashCode()
isn't possible.
long millis = System.currentTimeMillis();
To address your primary question finally: you can create this same behavior by creating methods that return objects instead of primitives (int, long, byte, etc.).
Upvotes: 1