In Java, a class is a blueprint for creating objects. Objects have properties or attributes that are defined in the class. In this blog, we will explore Java class attributes and their types, including instance variables, class variables, and local variables, with example code snippets to illustrate each concept.
Instance Variables:
Instance variables are variables declared within a class but outside of any method, and they are specific to each object of the class. Instance variables are created when an object of the class is created and destroyed when the object is destroyed. They have access modifiers such as public, private, or protected.
Example:
public class ExampleClass { public String name; // instance variable public void setName(String name) { this.name = name; // set instance variable } public String getName() { return name; // get instance variable } }
In the above example, we declare an instance variable called name within the ExampleClass. We then use setter and getter methods to set and get the value of the instance variable.
Class Variables:
Class variables, also known as static variables, are declared within a class but outside of any method, and they are shared by all objects of the class. Class variables are created when the class is loaded and destroyed when the program ends. They have the static keyword and access modifiers such as public, private, or protected.
Example:
public class ExampleClass { public static int count = 0; // class variable public ExampleClass() { count++; // increment class variable } public static int getCount() { return count; // get class variable } }
In the above example, we declare a class variable called count within the ExampleClass. We then use a constructor to increment the value of the class variable each time an object of the class is created. We also use a static method to get the value of the class variable.
Local Variables:
Local variables are declared within a method or block and have limited scope. They are created when the method or block is called and destroyed when the method or block ends. They do not have any access modifiers.
Example:
public class ExampleClass { public void exampleMethod() { int num = 10; // local variable System.out.println(num); // accessible } }
In the above example, we declare a local variable called num within the exampleMethod. The variable is only accessible within the method.
Conclusion:
Java class attributes play an essential role in creating objects and defining their properties. Understanding the different types of Java class attributes, including instance variables, class variables, and local variables, is essential to writing effective Java programs. With the examples provided, you can get started with Java class attributes and take your programming skills to the next level.