Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors and Strings Part 2Letter Example

Tags:

java

The issue I'm having is, while I believe that I've have set up everything correctly in the constructor, when I try to call the instance variable from of my new Letter instance fromto I seem to keep getting an error saying that the compiler can not find variable fromto. The goal is to get Dylan to appear in with the Text.

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() {

        Letter fromto = new Letter("Dylan", "April");

    }

    public static void main(String[] args) {
        System.out.println("Dear " + fromto.from);

    }

}
like image 996
user2872518 Avatar asked Dec 03 '25 04:12

user2872518


2 Answers

First of all, you should probably learn more about variable scope in Java. (Reading Sun's tutorials about Object-oriented Java-programming is probably a good idea)

The problem here is that the variable fromto is declared in a constructor and thus is only available from the scope of the constructor. Instead, get rid of that constructor (unless you really want to keep it, in which case you should make sure to initialize your from and to variables properly) and move the variable to your main function.

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 static void main(String[] args) {
        Letter fromto = new Letter("Dylan", "April");
        System.out.println("Dear " + fromto.from);
    }

}
like image 88
Simon Forsberg Avatar answered Dec 04 '25 17:12

Simon Forsberg


You need to first create a new instance of your Letter class before you can invoke fields and getter/setter-methods on that instance/object.

public static void main(String[] args)
{
    Letter myLetter = new Letter();
    System.out.println(myLetter.from);
}

Note the call on your private field from only succeeds as main is defined in the same class and therefore the created myLetter provides access to the field.

In practice you would define public setters and getters to access the private field.

like image 42
Roman Vottner Avatar answered Dec 04 '25 16:12

Roman Vottner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!