Learning Java: Attributes

The first time I heard about Attributes in Java I really thought it was a mistake, since I saw attributes as elements from CSS (Cascading Style Sheets). I thought It was something new on Java but apparently I was wrong, I used all the time and referred to it as “Variables”

Now lest talk about attributes, They are public constant or public variable that can be accessed directly, another word to refer to an attribute is “field”. As you can see in the example below “age” and “MY_AGE” are both attributes type int.

public class AttributeClass{
    int age;
    final int MY_AGE = 2019 - 1994;  

Attributes also can be modify. As we can see in the code below I instantiated the object “someone” and the object “donelys” from AttributeClass, Then I assigned the value 50 to attribute age.

    public static void main(String[] args) 
    {
        AttributeClass someone = new AttributeClass();
        AttributeClass donelys = new AttributeClass();
        someone.age = 50;
        System.out.println("someone age is: " + someone.age + " years old.");
        System.out.println("Donelys age is: " + donelys.MY_AGE + " years old.");

When a variable is set as final, it means that this variable become immutable and cannot be changed. As you can see in the code below I commented the change that I made to “MY_AGE” attribute because ill will return an error.

Also there are other classes that allows you to use their attribute as example in the code below we use “.length” attribute to retrieve the data of the array create.

        // donelys.MY_AGE = 12;
        // System.out.println("Donelys age is: " + Donelys.myAge );
        String[] array = {"hola","hello","bonjour", "klk"};
        System.out.println("Array length is: "+ array.length);
    }

}

Attribute, definitely are very useful when you need data from other classes, that is the magic that comes with a programming language that is object-oriented which makes coding mush easier and dynamically practical.

You can learn more about attributes here

Leave a comment

Design a site like this with WordPress.com
Get started