1#To create a static method, just add "@staticmethod" before defining it.
2
3>>>class Calculator:
4 # create static method
5 @staticmethod
6 def multiplyNums(x, y):
7 return x * y
8
9>>>print('Product:', Calculator.multiplyNums(15, 110))
10Product:1650
1Static keyword is used a lot in java.
2 Static means, you
3can access those static variables
4without creating an object,
5just by using a class name.
6This means that only one instance of
7that static member is created which
8is shared across all instances of the class.
9Basically we use static keyword when
10all members share same instance.
1// example on static method in java.
2public class StaticMethodExample
3{
4 static void print()
5 {
6 System.out.println("in static method.");
7 }
8 public static void main(String[] args)
9 {
10 StaticMethodExample.print();
11 }
12}
1// example on static variable in java.
2class EmployeeDetails
3{
4 // instance variable
5 int empID;
6 String empName;
7 // static variable
8 static String company = "FlowerBrackets";
9 // EmployeeDetails constructor
10 EmployeeDetails(int ID, String name)
11 {
12 empID = ID;
13 empName = name;
14 }
15 void print()
16 {
17 System.out.println(empID + " " + empName + " " + company);
18 }
19}
20public class StaticVariableJava
21{
22 public static void main(String[] args)
23 {
24 EmployeeDetails obj1 = new EmployeeDetails(230, "Virat");
25 EmployeeDetails obj2 = new EmployeeDetails(231, "Rohit");
26 obj1.print();
27 obj2.print();
28 }
29}
1// example on static block in java.
2public class StaticBlockExample
3{
4 // static variable
5 static int a = 10;
6 static int b;
7 // static block
8 static
9 {
10 System.out.println("Static block called.");
11 b = a * 5;
12 }
13 public static void main(String[] args)
14 {
15 System.out.println("In main method");
16 System.out.println("Value of a : " + a);
17 System.out.println("Value of b : " + b);
18 }
19}
1// example on static class in java.
2import java.util.*;
3public class OuterClass
4{
5 // static class
6 static class NestedClass
7 {
8 public void show()
9 {
10 System.out.println("in static class");
11 }
12 }
13 public static void main(String args[])
14 {
15 OuterClass.NestedClass obj = new OuterClass.NestedClass();
16 obj.show();
17 }
18}