简体   繁体   中英

Confused to understand program output

Here is a program

public class MovieTitle {
    public static void main(String[] args) {
        Movie one = new Movie();
        one.title = "I am title";
        one.playIt();
        System.out.println(one.title);
    }
}

class Movie {
    String title;
    void playIt() {
        this.title = "I am title of movie";
    }
}

The output is "I am title of movie" I am trying to understand it but till now I do not understand it properly. I want to know: Why does it not print "I am title"

Sequence of events:

// create a new Movie called "one"
Movie one = new Movie();

// at this point, one.title is still null

// set the title to "I am title"
one.title = "I am title";

// call playIt, which in turn ...
one.playIt();
   // sets the title to something else again
   => this.title = "I am title of movie";

If you printed the title before calling playIt , it would still show as "I am title".

Does this illustrate why:

public class MovieTitle {
    public static void main(String[] args) {
        Movie one = new Movie();
        System.out.println(one.title);
        one.title = "I am title";
        System.out.println(one.title);
        one.playIt();
        System.out.println(one.title);
    }
}

class Movie {
    String title;
    void playIt() {
        this.title = "I am title of movie";
    }
}

Here's the corresponding output:

java MovieTitle
null
I am title
I am title of movie

Cause you set when you call playIt() the title to "I am title of movie"; Try changing the order of the two lines

one.title = "I am title";
one.playIt();

If you trace out the calls, it should become fairly obvious.

Movie one = new Movie();

title will be NULL at this point (ie, it has had no value assigned)

one.title = "I am title";

Now your Movie object one has the title "I am title"

one.playIt();

Calls the playIt() method on one, which sets the title of "this" (which is one) to "I am title of movie"

You asign "I am title" to the title varible in object one of type Movie .

When you call method playIt() in the same object, varible title gets asigned another value "I am title of movie" .

If you invert the lines like so

one.playIt(); 
one.title = "I am title";

The output is going to be "I am title" , because you set this value, after you call playIt() method.

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