简体   繁体   中英

creating and initializing object in java

My question is very simple and novice. I have a class, and want to create instance of it. So should I use temporary variables and then assign the values using setters or should I create an object and then directly assign user input to setter.

class A {
int a;

A(){
    a=0;
}

A(int a){
    this.a=a;
}

}

Now how should I create objects?

  1. Should I use temporary variables and then use constructor to create object.
  2. Should I create object and directly assign user input to instance variable. for example
    aObj.setA(getUserInput());

Please advice.

To the first question: Either. Depends on a lot of things like:

  • Do you already know what the initial value or default value should be?
  • Would the class work properly/improperly without it set to anything at first?
  • Should the internal variable even have a setter at all?

Example: if I had

class bonkinator {
int timesBonked;

bonk(){
  timesBonked++;
}

getBonks(){
  return timesBonked; // thanks for the correction, Unihedron
}

...

Then chances are I wouldn't want other code to meddle with timesBonked, so I wouldn't give it a setter. So I'd want to set timesBonked to some initial value in the constructor, and whether or not that value is something I choose or something the calling code chooses depends on what we're trying to do.

To the second question: depends again.

  • Do you plan on re-using that thing from getUserInput()?
  • Would calling getUserInput() either annoy the user or re-run slow code (eg try to read something from a database that hasn't changed) for no added benefit?

Invoke new A(); or new A(42); in the same package.

Please see the following:

A a = new A(getUserInput());

A a = new A();
a.a = getUserInput();

There is not much difference but choose your preference in terms of code style: The Java compiler will optimize most of it.

That totally depends on the design but generally 2nd way is preferred in production code because you might add new variables in the class later and then if you change the constructor you might break existing code.

Also

A(){
    a=0;
}

is not necessary as instance variables get initialized with default values ie 0 for int.

There is no specific way to do that. It is purely based on what you wanna do. You can either have a setter to set the value after initializing the instance. Or you can have a parameter constructor and pass the value at the initializing point. Or even you can have fixed value if you want at the initializing. It is entirely up to you to decide what is the best approach for you to what you are trying to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM