Static Methods in Java Very useful for Selenium
Java static method
If you apply static keyword with any method, it is known as static
method.
- A static method belongs to the class
rather than object of a class.
- A static method can be invoked without
the need for creating an instance of a class.
- Static method can access static data
member and can change the value of it.
Example of
static method
- //Program of changing the common property of all objects(static field).
-
- class Student9{
- int rollno;
- String name;
- static String college = "ITS";
-
- static void change(){
- college = "BBDIT";
- }
-
- Student9(int r, String n){
- rollno = r;
- name = n;
- }
-
- void display (){System.out.println(rollno+" "+name+" "+college);}
-
- public static void main(String args[]){
- Student9.change();
-
- Student9 s1 = new Student9 (111,"Karan");
- Student9 s2 = new Student9 (222,"Aryan");
- Student9 s3 = new Student9 (333,"Sonoo");
-
- s1.display();
- s2.display();
- s3.display();
- }
- }
Output:
111 Karan BBDIT
222 Aryan BBDIT
333
Sonoo BBDIT
Another
example of static method that performs normal calculation
- //Program to get cube of a given number by static method
-
- class Calculate{
- static int cube(int x){
- return x*x*x;
- }
-
- public static void main(String args[]){
- int result=Calculate.cube(5);
- System.out.println(result);
- }
- }
Output:125
Restrictions for static method
There are two main restrictions for the static method. They are:
|
- The
static method cannot use non static data member or call non-static method
directly.
- this
and super cannot be used in static context.
- class A{
- int a=40;//non static
-
- public static void main(String args[]){
- System.out.println(a);
- }
- }
Output:Compile
Time Error
Q) why
java main method is static?
Ans)
because object is not required to call static method if it were non-static
method, jvm create object first then call main() method that will lead the
problem of extra memory allocation.
|
3) Java
static block
- Is used to initialize the static data
member.
- It is executed before main method at
the time of classloading.
Example
of static block
- class A2{
- static{System.out.println("static block is invoked");}
- public static void main(String args[]){
- System.out.println("Hello main");
- }
- }
Output:
static block is invoked
Hello main
Q) Can
we execute a program without main() method?
Ans)
Yes, one of the way is static block but in previous version of JDK not in JDK
1.7.
- class A3{
- static{
- System.out.println("static block is invoked");
- System.exit(0);
- }
- }
Output:static
block is invoked (if not JDK7)
Comments
Post a Comment