Using NON static class Methods Without reference

266 views Asked by At

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();
6

There are 6 answers

0
Mena On BEST ANSWER

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.

3
vikingsteve On

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.

0
mefi On

if method return type is instance of any class, you should chain calls on it and you dont need to create named variable.

This is used in Fluent interface api, where every method returns instance of "this" class.

Note: Be careful if you call many chained methods on different objects like:

collection.get(0).getAddress().getStreet().length();

because of possible NullPointerExceptions.

On the other hand, use of fluent api should be safe, because you always call it on "this" instance, so if api has not some strange bugs, it is safe and NPE should not occur.

1
GhostCat On

The other answers all correct, but I think they miss one crucial point: if you are new to Java ... don't waste your time thinking about such questions.

Don't get me wrong: it is always good to understand the programming language you are using in great depth; and it is also important to have some common sense to avoid "really stupid performance" mistakes.

But: don't worry about "performance" and spent hours to reduce the number of objects your program is dealing ... from 100 to 95. That is a complete waste of time.

If you intend to write programs that are used for a longer period of time, and by more than one person (and "good" programs tend to get there pretty fast) then it is much more important that your program is easy to read, understand, and change.

The only valid reasons to look into "performance" are:

  1. You are in the design phase; and as mentioned before one should avoid stupid mistakes that render your end-product "unusable" because of performance issues.
  2. You are actually confronted with "performance" issues. Then you should start profiling your application; and then, based on that analysis improve the "slow" parts.

In other words: don't try to solve "non-existing" problems. And unless your application is running in an embedded environment where every byte of memory and every CPU cycle can come at a certain prize ... don't worry about creating those Calendar objects 10, 100 or 500 times.

0
Adriaan Koster On

The general answer is no, because classes like Calendar are stateful and therefore require an initialized instance to be able to operate. If you do:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-1);

You are first calling a factory method getInstance() to create an instance of GregorianCalendar, which is the default concrete implementation of Calendar. It is initialized to the default timezone and locale and set to the current system time. This means it is different than another instance you create some milliseconds later.

Then, calling add(...) or other manipulation methods on your instance affects the calendar state, following the programmed calendar logic. If this was not a discrete instance but global (static) state, multiple threads would interfere with each other and cause very confusing results.

The same holds for example for the SimpleDateFormat class. It is often incorrectly set up as a field and re-used for formatting dates in a multi-threaded context (e.g. the handle method of a servlet). This will now and then cause erratic behavior because SimpleDateFormat is also stateful.

So the conclusion is: you need to create isolated instances of classes like Calendar and SimpleDateFormat because they are stateful and thus not thread-safe.

Bear in mind that sometimes you can optimize a bit by declaring your instance before any iterations you are doing, and then re-setting its state instead of creating a new instance on each iteration (after all, creating an instance of Calendar is indeed a bit expensive).

0
shankulk On

It is not only because method is not static. Understand that you cannot chain like this -- yesterdayDate = Calendar.getInstance().add(Calendar.DATE,-1).getTime(); because add() method does not return anything. If that method would have returned you the same calendar object, you could chain them without creating a reference.

Just to understand how chaining works, you can try creating your own methods those return objects and call other methods on them.