Java
In this tutorial we will learn about member variables of a class in Java programming language.
In the previous tutorial Class Introduction we learned about class. Now lets take about member variables that helps in storing data.
Java classes consists of member variables and methods.
Member variables hold the data whereas, methods of the class operates on the data.
Following are the points to note when naming member variables of a class.
continue
, return
etc.In the previous tutorial we created the PackagingBox
class. Now we will add the following member variables to hold data that characterise the class representing a real world box.
And all of the variables will be of data type double
.
So, our PackagingBox class will now look like the following.
class PackagingBox {
// member variables
double length;
double breadth;
double height;
double volume;
double weight;
double price;
}
We can use the following access modifiers to control the accessibility of member variables.
If access modifier of a variable is set to public
then it can be accessed by code from inside and outside the class.
If access modifier of a variable is set to private
then it can only be accessed by the code from inside the class.
If access modifier of a variable is set to protected
then it can be accessed by the code from inside the class. And it can be accessed by the code from child classes that inherits the parent class.
We will learn about inheritance in the later part of this tutorial series.
By default, access modifier of member variables is public
.
In the following example we are setting the access modifier of the member variables of the PackagingBox
class.
class PackagingBox {
// member variables
private double length;
private double breadth;
private double height;
public double volume;
double weight;
double price;
}
In the above example we have set the access modifier of length
, breadth
and height
variable to private
which means they can be only be accessed from inside the class.
We have set the access modifier of volume
variable to public
this means it can be accessed from both inside and outside the PackagingBox
class.
Note! We have not mentioned the access modifier for the weight
and price
variable so, by default they are set to public
.
So, far we have learned how to create a class and add member variables and set their access modifier.
In the next tutorial we will learn about methods that will help us to operate on the member variables.
Thanks for reading. See you in the next tutorial :-)
ADVERTISEMENT