简体   繁体   English

混淆理解程序输出

[英]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". 如果您在调用playIt之前打印了标题,它将仍然显示为“我是标题”。

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"; 因为您在调用playIt()时将标题设置为“我是电影的标题”; 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) 标题此时将为NULL(即,它没有分配值)

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" 在上调用playIt()方法,该方法将“ this”(这是一个)的标题设置为“我是电影的标题”

You asign "I am title" to the title varible in object one of type Movie . 您将类型为Movie对象onetitle变量分配为"I am title"

When you call method playIt() in the same object, varible title gets asigned another value "I am title of movie" . 当您在同一对象中调用方法playIt()时,可变标题将获得另一个值"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. 输出将是"I am title" ,因为您在调用playIt()方法之后设置了此值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM