Instance and Static variables and Methods in Java

What is an instance?

Creating an object from a class is known as class instance or creating a reference  / copy. In other words you can consider an object or instance is same thing. Example of class Circle is given below.

Circle c = new Circle();

c  is an object created from class circle and having an instance of class circle. Whereas instance variables belongs to a specific instance and instance methods are invoked by the instance of a class.

Static variables are shared by all instances of the same class and static methods are not tied to a specific object. Static variables and method can be accessed with class name.

Static variables

In class Circle numberOfObjects is a static variable and getNumberOfObjects() is a static method.

Creating object circle1 and circle2 updates the contents of numberOfObjects to 2. Accessing this variable or retrieving information from getNumberOfObjects() method will return 2 in every case. Clearly shown in figure.

What will happen, when another opbject circle3 is created. The value in numberOfObjects will be updated to 3.

public class Circle {
private double radius;
private static int numberOfObjects = 0; 

Circle() {
 radius = 1.0;
 numberOfObjects++; 
}

Circle(double newRadius) {
 radius = newRadius; numberOfObjects++; 
}

static int getNumberOfObjects() {
 return numberOfObjects; 
}

double getArea() {
 return radius * radius * Math.PI; 
}
}

Comments

  1. Reply

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.