a class in java has instance variables and instance methods. instance variables are also called state and instance methods are also called behaviour. for example a football is an object of a class Ball and has color, weight and shape as state and bounce is a behavior of ball.
so now what is called a static keyword? a class can have static member inside it. static member may be a variable or method. static member does not belong to any object rather than it belong to whole class. static keyword is used where we want to access some data without creating object because it does not belongs to any object.
for example in the below code am going to use static variable to keep track the number of objects created. so did you get what i mean? count does not belongs to any object.
class Ball
{
static int count;
String color;
String shape;
public void bounce(){
System.out.print("this ball can bounce");
}
public Ball(){
count = count+1;
System.out.print("the number of objects created ="+ count);
}
}
public class TestBall{
public static void main(String[] args)
{
Ball ball1 = new Ball();
Ball ball2 = new Ball();
}
}
you can create static method also
to access static member
the syntax is classname.membername. no need to create object to access static members.
note; static blocks always executes first.
No comments:
Post a Comment