I'm new to Java. I know the concept of static and non static method. I'm wondering if it's possible to use non static methods of a class without having to create a reference to it.
Like for example, for my program I'm working with Date objects, and I need to get yesterday's date in one of them. I know one possible way is like the following:
Calendar cal= Calendar.getInstance();
cal.add(Calendar.DATE,-1);
Date yesterdayDate = new Date();
yesterdayDate = cal.getTime();
Is there a way to do that without having to create the cal
reference that I will be using just once in the whole program?
Something like this (I know this is by no means a correct syntax):
Date yesterdayDate = new Date();
yesterdayDate = Calendar.getInstance().add(Calendar.DATE,-1).getTime();
If
Calendar
was following a fluent builder pattern, where i.e. theadd
method was adding, then returning the mutated instance, you would be able to.You're not, because
Calendar#add
returnsvoid
.But don't be fooled:
Calendar.getInstance()
does create an instance as indicated - you're just not assigning it to a reference.