Reputation: 21
what is the difference of this two codes snippet
import javax.swing.*;
public class Mainframe extends JFrame {
private JLabel nameLbl = new JLabel( "Name" );
private JTextField nameTf = new JTextField( "10" );
}
import javax.swing.*;
public class Mainframe extends JFrame {
private JLabel nameLbl;
private JTextField nameTf;
public Mainframe() {
nameLbl = new JLabel( "Name" );
nameTf = new JTextField( "10" );
}
}
Upvotes: 0
Views: 118
Reputation: 41
Creating object of any variable in constructor and in declaration is similar
see the example below:
public class DemoClass {
String str;
String newStr = new String("I am initialized outside");
public DemoClass() {
System.out.println(newStr);
str = new String("I am initialized inside");
System.out.println(this.str+"\n");
}
public static void main(String[] args) throws Exception {
DemoClass dc = new DemoClass();
}
}
In the above example you can see -- In the constructor the variables are getting initialized, as the object of DemoClass is already created in the memory by JVM before calling the constructor.
Constructors are meant only for initializing any instance variable.
Flow of creating object: Before creating the DemoClass object, JVM will create the depended object i.e. newStr will be created first, and then DemoClass object will be created.
Upvotes: 1
Reputation: 669
The explicit initialization of object fields is copied into every constructor (non-argument constructor or argument constructors) by compiler.
Upvotes: 0
Reputation: 6675
Internally ,the instance variable declaration and your constructor code becomes same in the bytecode.Even the initializer block gets merged in the following order :-
1)Instance member declaration
2)All initializer block declarations in the order of their occurence
3)Constructor code
After compilation,bytecode treats it as one
Upvotes: 0
Reputation: 36304
There is not much difference in your particular case.
But generally, if you wanted to initialize your object with some custom values, then you do it in a constructor.
example :
public Mainframe(String name, String number) {
nameLbl = new JLabel( name );
nameTf = new JTextField( number );
}
Upvotes: 1
Reputation: 68945
Functionality wise there is none. But if you have multiple constructors in second case and if you are creating Object via non default constructor then the instance variables will remain null.
Upvotes: 0