简体   繁体   中英

non static method calls without creating an object inside onCreate()

I heard that in java Instance (non-static) methods work on objects and to invoke non static method requires to have a reference to an instance. But here in this Java(Android) code non Static method is called without creating an object inside onCreate() method and no errors. I wonder why is that?

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    newGame();


}


private void newGame(){

    // code here

}

}

sorry for my low knowledge in java

It is because the method newGame() is the member method of your class/activity name MainActivity. According to OOP concepts, you don't need class object if you are calling member method of same class. It is same like member variable. That is what you want.

There is an instance. Java objects are created with a constructor, since your MainActivity didn't include one you got a default one. It looks like,

public MainActivity() {
  super();
}

Then your onCreate() is invoked on that instance.

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