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?

14th Nov 2022, 4:20 PM
Galstyan
Galstyan - avatar
12 ответов
+ 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
14th Nov 2022, 5:26 PM
A͢J
A͢J - avatar
+ 2
Where is code?
14th Nov 2022, 4:43 PM
A͢J
A͢J - avatar
+ 2
Galstyan Both methods are in same class so you can access one method inside another method no need to create object.
14th Nov 2022, 5:07 PM
A͢J
A͢J - avatar
+ 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.
14th Nov 2022, 5:12 PM
A͢J
A͢J - avatar
+ 2
Galstyan In your example onCreate and myFunc both are non-static so you can access myFunc inside onCreate
14th Nov 2022, 5:14 PM
A͢J
A͢J - avatar
+ 2
A͢J You can’t imagine how grateful I am. Thank you very much kind man!! 🙏🏻
14th Nov 2022, 5:34 PM
Galstyan
Galstyan - avatar
+ 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 } }
14th Nov 2022, 5:00 PM
Galstyan
Galstyan - avatar
+ 1
A͢J Help to understand whats going on pleasse…
14th Nov 2022, 5:03 PM
Galstyan
Galstyan - avatar
+ 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
14th Nov 2022, 5:15 PM
Galstyan
Galstyan - avatar
0
A͢J so what about java main function?
14th Nov 2022, 5:09 PM
Galstyan
Galstyan - avatar
0
A͢J If u wanna call a function inside the main function then your function to hafta be static inside the same class
14th Nov 2022, 5:09 PM
Galstyan
Galstyan - avatar
0
A͢J its work only for main function? not in onCreate()?
14th Nov 2022, 5:11 PM
Galstyan
Galstyan - avatar