+ 1
What is the use of using static keyword in methods and variables?
4 Respuestas
+ 3
Two important things you need to know about static are-
1) A variable declared static retains it's value during function calls.
2) To call a static method of a class you need not create an instance of that class.
+ 3
Coder's Crux You mentioned that static variables can't be accessed using an instance of the class in which they are declared. But that is not true. It is just that static members give us the privilege to call them without creating an instance of that class. But they can also be called using an instance of the class.
public class Program
{
public static void main(String[] args) {
System.out.println(A.a);
A obj = new A();
System.out.println(obj.a);
}
}
class A{
static int a = 10;
}
0
Static variables or functions cannot have a copy of themselves, which means they are shared between multiple instances of the same class. To access static you cannot use an instance object, you will have to ise the actual class name. Examples of static classes are Math, Console, Convert and more. Hope it made it a little more clear.