+ 2
Why do we use static? Eg: Static int...?
4 Réponses
+ 16
when you add static to a method declaration it makes it possible to use the method without first creating an object of that method
+ 9
the variables which are preferred with static called as static variables which will be saved In method area as a part of .class file.so that user can access those variables without creating an object. we can access static variables by using class name. As it is no way related to the object.
class College
{
static String college_name;
int student_id;
String student_name;
}
In the above code you can see that only college_name is declared as static because college _name is similar for all the students in that college. so creating object for each student college name is a waste of memory. so it was declared as static it means memory allocation will be done at once at method area and that will be shared by all students.
whereas student_id and student _name are declared as non-static because those will be unique for each and every student.so compulsory we should create object for each student, non-static variables will be stored in heap area as a part of object.
+ 4
share variable across all objects of a class, and save memory.
0
Thanks a million.