简体   繁体   中英

What happens when you put a .method after an object?

i am trying to understand why this won't run. I am thinking that I may need to import a package. I would also like to know what happens in the class LocalVariables on the the line myObject.f();

I think that I have just instantiated myObject on the previous line but am I calling the f method with myObject.f(); ????? I don't understand what is supposed to happen on that line.
Any help would be appreciated.

class MyObject{
 static short s = 400; //static variable
 int i = 200;  //instance variable

 void f() {
     System.out.println("s = " + s);
     System.out.println("i = " + i);
     short s = 300;  //local variable
     int i = 100;  //local variable
     double d = 1E100;  //local variable
     System.out.println("s = "+s);
     System.out.println("i = " +i);
     System.out.println("d = " + d);
          }
     }


class LocalVariables{
    public static void main(String[] args){
        MyObject myObject = new MyObject();
        myObject.f();
    }
}

Yes, you are calling the f() method. Thus flow of control will jump to the top of the f() function and execute those statements one by one.

Once it is done, it will go back to the main method, resuming where it had left off. This doesn't mean anything here, since myObject.f() is the last line, but if you had more code then that would be executed once the f() method returns.

Well executing this should have printed a few lines

s = 400
i = 200
s = 300
i = 100
d = <something>

Did anything of this sort appear in your output?

change void f() to public void f() { //Code... }

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