What is static variable?
- static
variable is used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of
students etc.
- static
variable gets memory only once in class area at the time of class loading.
What is 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.
Why main method is static?
Because object is
not required to call static method if It were non-static method,jvm creats
object first then call main() method that will lead to the problem of extra
memory allocation
What is static block?
- Is used
to initialize the static data member.
- It is
excuted before main method at the time of classloading.
Can we execute a program without
main() method?
Ans) Yes, one of the
way is static block
What if the static modifier is
removed from the signature of the main method?
Program compiles.
But at runtime throws an error "NoSuchMethodError".
What is difference between static
(class) method and instance method?
static or class method
|
instance method
|
1)A
method i.e. declared as static is known as static method.
|
A
method i.e. not declared as static is known as instance method.
|
2)Object
is not required to call static method.
|
Object
is required to call instance methods.
|
3)Non-static
(instance) members cannot be accessed in static context (static method,
static block and static nested class) directly.
|
static
and non-static variables both can be accessed in instance methods.
|
4)For
example: public static int cube(int n){ return n*n*n;}
|
For
example: public void msg(){...}.
|
No comments:
Post a Comment