+ 1
Why is the keyword static used while declaring methods?
3 odpowiedzi
+ 6
You want some functionality of class but you don't need to make object, it will cost you unnecessary memory and in bigger programs slower execution, that's when you use static
+ 5
Because they belong to a class rather than an object.
Example:
public Class Program{
public static int getOne (){
return 1;
}
public int getTwo() {
return 2;
}
public static void main(String[] args) {
getOne(); //doesn't need an object because it's static
Program x = new Program();
x.getTwo(); // we needed to create object x because method wasn't static
}
}
+ 3
You use static keyword simply to declare a method to be static.
When you define objects using constructors, the objects will automatically inherit the methods from their class, but the objects will not inherit static methods.