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.
Restrictions for
static method
There are two main restrictions for the static method. They are:
|
1. The
static method can not use non static data member or call non-static method
directly.
2. this
and super cannot be used in static context.
Example 1: public static void main itself is a static method
class Example5{
static int i;
static String s;
public static void main(String args[]) //Its a
Static Method
{
Example5 obj=new Example5();
//Non Static variables accessed using
object obj
System.out.println("i:"+obj.i);
System.out.println("s:"+obj.s);
}
}
Output:
i:0 s:null
Example
: 2
class Languages {
public static void main(String[] args) {
display();
} static void display() {
System.out.println("Java is my favorite programming language.");
}
}
Output:
Java
is my favorite programming language.
|
No comments:
Post a Comment