Course Content
Introduction to Java
Today we'll learn something very important in Java programming - instance variables, the this
keyword, and static variables and methods. Are you ready to learn? Let's go!
Instance Variables
Think about a toy box, it has a lot of toys inside it, right? And each toy has its name and color, right? In Java, we use instance variables to store the information about each object. Like each toy's name and color, each object has its own set of instance variables. Let's look at an example:
Main.java
In the example above, name
and color
are instance variables. And each toy we create will have its own set of these variables.
The this keyword
Now, let's say we want to set the name and color of a toy. We can use the this
keyword to refer to the current object. Like this:
Main.java
Static Variables and Methods
Sometimes, we want to store information or write a method that's the same for all objects. That's where static variables and methods come in! They are not tied to any specific object. They belong to the class as a whole.
Static Variables
Static variables are shared among all objects of the class. So if you change the value of a static variable in one object, it will change for all objects.
For example, let's say you have a class called ToyBox
, and you want to track how many toys are in the box. You can use a static variable called "count" to do this.
Here's how it would look:
Main.java
Every time you create a new ToyBox object, it will have access to the count
variable. If you want to increment the count, you can do it like this:
Main.java
Or you can access the count variable directly using the class name like this:
Main.java
Static Methods
Static methods are also shared among all class objects and can only access static variables. They are called using the class name and not an object of the class.
For example, let's say you want to increment the count of toys in the box. You can write a static method called incrementCount
to do this.
Here's how it would look:
Main.java
Now, you can call the incrementCount
method using the class name like this:
Main.java
There is a key point to be remembered. Static methods can only access static variables. You can’t use instance variables inside the static methods. And that's it! These are the basics of using static variables and methods in Java. You can use them to store information shared among all class objects and write methods that can be called without creating an object of the class. I hope this helps clarify how to use static variables and methods in Java!
What is the "this" keyword used for in Java?
Select the correct answer
What is the difference between an instance variable and a static variable in Java?
Select the correct answer
Section 3.
Chapter 1