Java Class Attributes
In the previous chapter, we used the term "variable" for x in the example (as shown below). It is actually an attribute of the class. Or you could say that class attributes are variables within a class:
Create a Class
Create a class called "Main"
with two attributes: x and y:
Create a class named "Main" with a variable x:
Example
public class Main { int x = 5; int y = 3; }
Accessing Attributes
You can access attributes by creating an object of the class, and by using the dot syntax (.):
The following example will create an object of the Main class, with the name myObj. We use the x attribute on the object to print its value:
Create an object called "myObj"
and print the value of x:
Example
public class Main { int x = 5; public static void main(String[] args) { Main myObj = new Main(); System.out.println(myObj.x); } }
Modify Attributes
You can also modify attribute values::
Set the value of x to 40:
Example
public class Main { int x; public static void main(String[] args) { Main myObj = new Main(); myObj.x = 40; System.out.println(myObj.x); } }