This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Which one is the better way of code writing?
Hi everyone,
I would like to know if there is any difference between two initialization methods below. If so, which method is considered as a best practice? Thanks in advance.
Class Foo {
List myList = new ArrayList();
}
Class Foo {
List myList;
public Foo() {
myList = new ArrayList();
}
}
if you know what you are going to initialize a class member to, it is better to do it as the first example. In that case, you are creating a new ArrayList. You should also make it private final unless you intend to change it through class methods.
I only initialize things in the constructor if the constructor takes arguments that are applied to members - otherwise I do it outside of it.
I think it's a matter of style... I prefer the former when possible, but the latter when necessary.
Personally I prefer the second (creating new objects in constructor). But there's no difference between them.
The only difference maybe if you have two objects created by both methods, object which is created by first method is created first and object which is created in constructor would be created after it.
Related
What is the most correct and/or efficient way in terms of time & memory consumption to write simple pojo class containing ArrayList? (Regarding java mechanism for references, pass by ref', assignments etc.):
public class MyClass {
//1. Do we need to initialize here?
public List<String> mList = new ArrayList<>();
//2. Do we need to declare D. Constructor?
public MyClass() {}
//3. Need to initialize the list here or just pass?
public MyClass(List<String> list) {
this.mList = list;
}
//4. Better way for copy/assignment?
public void setMlist(List<String> list) {
this.mList = list;
}
public List<String> getMList() {
return this.mList;
}
}
Do we need to initialize here?
No, initialize it only when you need it. Make sure to check for null if there is possibility of using it without being initialized.
Do we need to declare D. Constructor?
If you do nothing in it, I don't really see the point of having it. Note that some people prefer to still declare it writing a comment in it and indicate that it should do nothing :
public MyClass(){
//NOP
}
See NOP. This won't change anything related to memory usage. However logically, the default constructor should initialize the list instead of initializing it at the beginning. So we have two options, we pass one that already exists (with the parameterized constructor) or we use the default constructor and create an empty list.
Need to initialize the list here or just pass?
Just pass, else what would be the point of receiving it as an argument ? If you initialize it and re-assign that would make no sense. You may want to check if the received one is null and initialize it otherwise.
Better way for copy/assignment?
If really you want to make a copy, you might want to check Collections#copy. However, this is not the point of setter, what you have done here is correct.
This is impossible to answer without knowing about your intentions. There's a surprisingly large number of design decisions you have to make, even when writing a "simple pojo class containing ArrayList". Here are 8 off the top of my head, but there are many, many more.
Do you want to make the field public or private? (probably private.)
If private, do you want to provide a get method?
Do you want to provide a set method, or do you want the field to be initialized once and for all in the constructor?
Should the argument to your constructor and/or set method only accept a List<String> or will you allow something more general, such as Collection<? extends CharSequence>?
Do you want people using your class to be able to modify mList? (This is different from reassigning mList.)
Do you want to write subclasses, or do you want the class to be final?
If you want to write subclasses, do you want to make any of the methods final?
Do you want to provide a constructor with no argument that initialises the ArrayList to a sensible default value?
The most subtle one of these questions is the 5th. Suppose somebody does this
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
myClass.setMList(list);
and then later does this
System.out.println(myClass.getMList());
They may expect to see [a, b, c], but this may not happen because it is possible to modify the internals of myClass in between. For example:
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
myClass.setMList(list);
list.remove(1); // Modifies the List stored by myClass
System.out.println(myClass.getMList()); // prints [a, c]
If you don't want this kind of thing to be possible you'll have to write a class that copies List objects in the constructor, setter and getter. This will have consequences for performance (but will be tiny for small lists).
There are no right or wrong answers. You need to think through who is using the class, why they need it, and weigh up all the relevant factors when answering all of the above questions.
I am just starting out with java and I was wondering if any one could tell me is there a way to use an interface in a linkedlist. I have an interface called Question. I implement two classes from it: 1) MCQ 2) TrueFalse. I want a list of Question interface so that I can have random MCQs and TrueFalse in my list. Is it possible in Java? This is what I have go so far:
private static List<Question> Questions; //declaring in a class
Questions = new LinkedList<Question>(); //creating a linkedlist
And then simple adding MCQ's and TrueFalse to it.
Yes, you can use interfaces as the type argument to a linked list.
You should define enough methods in the interface to be able to handle all the useful functionality for your MCQs and TrueFalses, without having to downcast.
What you write is true and valid.
questions = new LinkedList<Question>(); //creating a linkedlist
That accepts all type of Question objects. To add MCQ's to it, the only rule is your MCQ and TrueFalse must implement Question interface. If you are already doing it you are fine.
But be careful about accessing them. Since you are getting randomly, you never know which object you are getting back. If you assign a MCQ to TrueFalse, ClassCastException will occur. To avoid such situations, always use it's type (Question).
Which method is better?
Creating objects in class constructor:
public class Menu {
private JButton start;
// ...
public Menu() {
start = new JButton("Start");
// ...
}
}
or creating objects while variable declaration?:
public class Menu{
private JButton start = new JButton("Start");
// ...
public Menu(){
// ...
}
}
and what is the difference?
Both variants are OK , but I prefer the second one since there's one statement less - to write, but more important to read and to maintain.
There is no runtime difference in this case, AFAIK.
Sometimes, when following the second variant, you can even remove the custom contructor altogether.
Already answered here , The question was for C#, but the logic is still the same.
It is said to follow these rules, which are pretty complete:
1. Don't initialize with the default values in declaration (null, false, 0, 0.0...).
2. Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field.
3. If the value of the field changes because of a constructor parameter put the initialization in the constructors.
4. Be consistent in your practice. (the most important rule)
Read the comments for more details.
Initialisation within the constructor does allow you to deal easily with exceptions, which can be helpful as your code base matures.
But some folk say that declaration at the point of initialisation is more readable. But then the order that fields appear in the source becomes important.
Aside from the exception consideration, it's down to personal opinion.
The second method is better.
There are four different ways to create objects in java:
A. Using new keyword
This is the most common way to create an object in java. Almost 99% of objects are created in this way.
MyObject object = new MyObject();
B. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("com.sample.MyObject").newInstance();
C. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
D. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
There is no difference. I usually prefer to use the second way, but if you need to have exception handling, then you need to use the first way.
With the first option you could add more logic to object initialization (exception handling, logging, etc..).
NOTE: if you would like to consider Dependency Injection at some point then initialization on declaration is not an option.
You can create objects in different ways. As Neeraj already said Lazy Initialization can sometimes be the preferred way.
In your example, where you need your button as soon as the parent Object is instantiated, you can use both ways.
But you can also consider the following example, where you create the child object exactly at the time you need it.
public class MyObject{
private List<String> myList = null;
public MyObject(){
//do whatever you want
}
public void add(String toAdd){
if(myList == null){
myList = new ArrayList<String>();
}
myList.add(toAdd);
}
}
You can craete object both way and i recommend you to use
JButton start = new JButton("Start");
Best way is to create and initialize object in the constructor of a class.
This question already has answers here:
Return multiple values from a Java method: why no n-tuple objects?
(7 answers)
Closed 8 years ago.
While working with Java Applications, I feel most of the times one question : Why Java doesn't support multiple return values of methods?
I know that people who designed Java, must have done thinking about this topic but I didn't get any answer or particular reason while thinking myself.
If all the values are of the same type, you can just return an array of them:
public String[] myMethod{} {}
If they are not, they you have multiple options:
The ugly one is to cast everything into an Object and return either:
public Object[] myMethod{} {}
or
public List<? extends Object> myMethod() {}
The problem with these implementations is you really don't know what's what in the object/list unless you look at the method implementation. So it can be a shortcut if you know noone else is going to use this.
There's cleaner but a bit more time consuming. But it's usually a good practice because carries more information:
Say you want to return two values, an int and a String. You need to design an object that represents those two (or more values):
public class MyResponse {
public String myString;
public int myInt;
}
And return an instance of MyResponse. Note that here I made the attributes public. There are multiple schools of thoughts around this. Some will prefer to make them private and add getter/setter methods. That's homework for you.
Conceptually Java method should acomplish only one action on data and return concrete result. If you could not decide what should return your method this is a cause of bad OOP design of the class.
If you just want to return a several objects (one type of objects) from method you should use collections or arrays as #mprivat said.
This question already has answers here:
What are the best practices for determining the tasks of Constructor, Initialization and Reset methods
(5 answers)
Closed 9 years ago.
In Java, but in other OO languages as well, is there a difference between initializing an attribute in its definition, as in
class Example {
public Sample sample_attribute = new Sample();
}
and using a constructor to initialize it?
class Example {
public Sample sample_attribute;
public Example() {
sample_attribute = new Sample();
}
}
I could not think of any practical difference, is there one? Otherwise, are there cases in which one method is better than the other, even if they have the same result?
The initialization order is matter here.
Set fields to default initial values (0, false, null)
Call the constructor for the object (but don't execute the body of
the constructor yet)
Invoke the constructor of the superclass
Initialize fields using initializers and initialization blocks
Execute the body of the constructor
So, first case will be initialize the variable sample_attribute in 4th step, second will initialize the variable sample_attribute in 5th step. It's all depends on your requirement.
If you want to access any of the variables from Constructor, you need to use 1st case.
When you initialize your fields with information which gets passed into the constructor, you have no other choice but to initialize in the constructor. Otherwise, I prefer initialization on the spot as it saves me lines of code I have to read later.
These two versions are equivalent. But if new Sample() threw a checked exception you wouldn't be able to initialize it at field declaration