+ 2
What is Static method in java?
please someone explain in detail with example what does this line mean... static is a method that can be run without creating an instance of the class containing the main method also, What is instance of the class?
5 Respostas
+ 5
For those who didn't understand the advantage of declaring a variable as static, here is a clear explanation :
Let's say that you have the following Class, of students from the same school :
Class student {
int ID;
String FirstName;
String LastName;
String School = "xyz";
}
So here, the school is common for all objects ( all students are from one school only ), if I declare School as a static variable, the School field will get memory only once, if I don't declare it as static like in the example above, it will get memory each time a new Student (an object) is created and that is a waste of memory.
So one of the main reasons why we declare variables as static is to make programs more efficient in terms of memory.
by OUSSAL BENAMEUR(she explained very well)
hope it helps
+ 4
Objects can be called as instance of a class.
class Lamp { //class name
boolean isOn;
void turnOn() {
isOn = true;
}
void turnOff() {
isOn = false;
}
}
class ClassObjectsExample {
public static void main(String[] args) {
Lamp l1 = new Lamp(); // create l1 object of Lamp class
Lamp l2 = new Lamp(); // create l2 object of Lamp class
}
}
+ 3
U welcome 😊
+ 2
Instance of a class is the object, static methods are accessed through the class not object e.g. Class.StaticMethod();. Static methods also can’t use non static variables.
+ 1
chamuRoyal thank you :)