0
Android studio- Java
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?
12 Respostas
+ 3
Galstyan
Check this example:
public class Program
{
public static void main(String[] args) {
example1();
Program p = new Program();
p.example2();
}
private static void example1() {
System.out.println("Static method");
}
private void example2() {
System.out.println("Non-Static method");
example3();
}
private void example3() {
System.out.println("Non-Static method 1");
}
}
Here main method and example1 both are static method so you can access example1 method inside main method directly.
But you cannot access non-static method example2 inside main method directly so here you need an object.
example2 and example3 both are non-static so you can directly access example3 method inside example2 method
+ 2
Where is code?
+ 2
Galstyan
Both methods are in same class so you can access one method inside another method no need to create object.
+ 2
Galstyan
main method is a static method so if you access another method inside it then you need to make it static.
A class can have different types of method static and non-static
a static method can access only static variable or static method.
+ 2
Galstyan
In your example onCreate and myFunc both are non-static so you can access myFunc inside onCreate
+ 2
A͢J You can’t imagine how grateful I am. Thank you very much kind man!! 🙏🏻
+ 1
public class MainActivity extends AppCompactActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myFunc();
}
public void myFunc(){
// code here
}
}
+ 1
A͢J Help to understand whats going on pleasse…
+ 1
Only calling the function inside the onCreate function confused me but now it's clear very clear!!!
Thank you very much! You saved me! A͢J
0
A͢J
so what about java main function?
0
A͢J
If u wanna call a function inside the main function then your function to hafta be static inside the same class
0
A͢J its work only for main function? not in onCreate()?