Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NON static class Methods Without reference

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();
like image 785
mahmoud Avatar asked Dec 02 '25 23:12

mahmoud


2 Answers

If Calendar was following a fluent builder pattern, where i.e. the add method was adding, then returning the mutated instance, you would be able to.

You're not, because Calendar#add returns void.

But don't be fooled: Calendar.getInstance() does create an instance as indicated - you're just not assigning it to a reference.

like image 173
Mena Avatar answered Dec 05 '25 04:12

Mena


What you are referring to is the known Builder pattern.

The Calendar class isn't build to support the builder pattern, but there are many other classes / apis where it is.

For example, DateTimeFormatterBuilder from joda time.

DateTimeFormatter monthAndYear = new DateTimeFormatterBuilder()
    .appendMonthOfYearText()
    .appendLiteral(' ')
    .appendYear(4, 4)
    .toFormatter();

You can always go ahead and create your own builders. (In your example, CalendarBuilder).

But you should be aware that the Calendar class is generally regarded as evil - it's not thread safe, for one. Newer alternatives are joda time and the java 8 api's.

like image 30
vikingsteve Avatar answered Dec 05 '25 03:12

vikingsteve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!