You need to instantiate your Letter
in the right scope. If you only need it inside the main method, the best place to create your instance is right at the beginning of the method block:
public class Letter {
private String from; // Sets from instance variable to be stored
private String to; /// Sets to instance vaariable to be stored
public Letter(String from, String to) {
this.from = from;
this.to = to;
}
public Letter() {
}
public static void main(String[] args) {
Letter letter = new Letter("Dylan", "April");
System.out.println("Dear " + letter.from);
}
}
About the no-args constructor, it is a good practice to declare one if the instance variables from
and to
are optional, so that you can also instantiate letter with the syntax new Letter()
. If you do not declare any constructors, the compiler provides a empty constructor by default.
Actually, whenever you can, it is a good thing to follow JavaBeans conventions. Quoting Wikipedia:
- The class must have a public default constructor (no-argument). This
allows easy instantiation within editing and activation frameworks.
- The class properties must be accessible using get, set, is (used for
boolean properties instead of get) and other methods (so-called
accessor methods and mutator methods), following a standard naming
convention. This allows easy automated inspection and updating of bean
state within frameworks, many of which include custom editors for
various types of properties. Setters must receive only one argument.
- The class should be serializable. It allows applications and
frameworks to reliably save, store, and restore the bean's state in a
fashion independent of the VM and of the platform.