Pedram
Pedram

Reputation: 684

different ways to create a new instance of a class?

I know there are a bunch of different ways to create an instance of a class, which I don't know many of, But I've just seen this kind of definition.
I'm not even sure if it's making a new instance!! Little misunderstanding and I can't digest it well.

Could anyone explain the code below?

new timer().scheduleAtFixedRate(new TimerTask() {
          @Override
        public void run() {
            ...
        }
    }, 0, 1000);

Is there any difference between the one above and the one below? As long as they're the same, which one do you prefer?

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
          @Override
        public void run() {
            ...
        }
    }, 0, 1000);

Upvotes: 0

Views: 117

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56433

Is there any different with this one? As long as there are same, which one do you prefer?

Firsly, I'd like to point out what @Carcigenicate has said within the comments.

" I wouldn't expect the first to compile, unless timer() is a constructor, in which case the two are the same."

I would assume that was a mistake and you meant to write Timer() as a constructor invocation.

The code below creates an anonymous object of type Timer and this is good to use when you want to perform a certain task there and then but don't expect to use the Timer object again. Basically, you won't be able to reuse the object again later on in your code.

new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                ...
            }
     }, 0, 1000);

The code below is equivalent to the one above except this one is not an anonymous object and we can reuse the object later on in our code.

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            ...
        }
    }, 0, 1000);

As long as they're the same, which one do you prefer?

It really depends on the circumstances and the situation but if i were to chose I'd go with the second one, for the reasons I have stated above.

Upvotes: 1

Related Questions