Java Class Attributes
In the previous example, we created a variable in a Java class MyClass and it is known as attribute of the class. In other words, class attributes are variables within a class. The class attributes are also called as fields.
Example
In the below example, we create class attributes “text” and “x”:
public class MyClass { String text = "Hello World!"; int x = 100; }
Accessing Attributes
The class attributes can be accessed using the dot syntax(.)
Example
In the below example, we create a object “myObj”. We print the class attributes using the dot syntax:
public class MyClass { String text = "Hello World!"; int x = 100; public static void main(String args[]){ MyClass myObj = new MyClass(); System.out.println(myObj.text); System.out.println(myObj.x); } }
Output
Hello World! 100
Modify Attributes
The class attributes can also be modified.
Example
In the below example, we override the value of class attributes “text” and “x” in the main class:
public class MyClass { String text = "Hello World!"; int x = 100; public static void main(String args[]){ MyClass myObj = new MyClass(); myObj.text = "Friends"; myObj.x = 50; System.out.println(myObj.text); System.out.println(myObj.x); } }
Output
Friends 50