“Método estático” Respostas de código

Métodos estáticos

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
Nutty Nightingale

Método estático

// 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 
    }
}
Harith Dzikri

Métodos estáticos

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()
Repulsive Reindeer

Respostas semelhantes a “Método estático”

Perguntas semelhantes a “Método estático”

Procure respostas de código populares por idioma

Procurar outros idiomas de código