+ 1

Why we use static to call the object can't we use another method.

class MyClass { static void sayHello() { System.out.println("Hello World!"); } public static void main(String[ ] args) { sayHello(); } }

7th Mar 2018, 12:27 PM
Ajay Verma
Ajay Verma - avatar
4 Respuestas
+ 3
you can remove static keyword. But in that case you have to create an object of MyClass class so as to access its non-static member function sayHello(). class MyClass { void sayHello() { System.out.println("Hello World!"); } public static void main(String[ ] args) { MyClass obj = new MyClass(); obj.sayHello(); } } However, using static is better in this case as it makes your code compact.
7th Mar 2018, 6:24 PM
cHiRaG GhOsH
cHiRaG GhOsH - avatar
+ 13
to avoid creating object of a class to access a method //in java
7th Mar 2018, 12:48 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 9
Can you provide us with more context? Perhaps a code snippet to show the situation you are talking about?
7th Mar 2018, 12:38 PM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Anything static is permanently assigned memory, and it will not be erased until the program is closed. This is useful in cases where you need to keep track of something throughout the program, or when you need default values for a variable.
7th Mar 2018, 12:46 PM
apex137
apex137 - avatar