xxxxxxxxxx
public class StaticMethod {
static int x = 10;
void display1() {
display2(); //We can call not static
System.out.println("I'm not static method!");
}
//We did not call non static from static method
static void display2() {
System.out.println(" "+x);
System.out.println("I'm static method!");
}
}
xxxxxxxxxx
A static method belongs to the class rather than the object.
There is no need to create the object to call the static methods.
A static method can access and change the value of the static variable
xxxxxxxxxx
class Employee(object):
def __init__(self, name, salary, project_name):
self.name = name
self.salary = salary
self.project_name = project_name
@staticmethod
def gather_requirement(project_name):
if project_name == 'ABC Project':
requirement = ['task_1', 'task_2', 'task_3']
else:
requirement = ['task_1']
return requirement
# instance method
def work(self):
# call static method from instance method
requirement = self.gather_requirement(self.project_name)
for task in requirement:
print('Completed', task)
emp = Employee('Kelly', 12000, 'ABC Project')
emp.work()
xxxxxxxxxx
// Java program to demonstrate restriction on static methods
class Test
{
// static variable
static int a = 10;
// instance variable
int b = 20;
// static method
static void m1()
{
a = 20;
System.out.println("from m1");
// Cannot make a static reference to the non-static field b
b = 10; // compilation error
// Cannot make a static reference to the
// non-static method m2() from the type Test
m2(); // compilation error
// Cannot use super in a static context
System.out.println(super.a); // compiler error
}
// instance method
void m2()
{
System.out.println("from m2");
}
public static void main(String[] args)
{
// main method
}
}
xxxxxxxxxx
class Repo {
static getName() {
return "Repo name is modern-js-cheatsheet"
}
}
// Note that we did not have to create an instance of the Repo class
console.log(Repo.getName()) // Repo name is modern-js-cheatsheet
let r = new Repo();
console.log(r.getName()) // Uncaught TypeError: r.getName is not a function