Java - OOP - Attributes

In Java, an attribute is a variable that is associated with an object. Attributes define the properties of an object and are used to store data. Attributes are also called instance variables because each object has its own set of attributes.

Here is a tutorial on attributes in Java:

Defining attributes: To define an attribute in Java, you must declare it within the class definition. For example, if you want to define an attribute called "age" for a class called "Person", you would write:

public class Person {
    int age;
}

Accessing attributes: To access the value of an attribute in Java, you must use the dot notation. For example, to access the value of the "age" attribute for a Person object called "john", you would write:

john.age

Initializing attributes: When you create an object in Java, its attributes are automatically initialized to their default values. For example, if the "age" attribute is an integer, it will be initialized to 0. However, you can also initialize attributes explicitly using a constructor or a setter method. For example:

public class Person {
    int age;
    public Person(int age) {
        this.age = age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

Encapsulation: In Java, attributes are typically defined as private to ensure encapsulation. Encapsulation means that the internal workings of an object are hidden from the outside world, and only the object's public methods are accessible. To access a private attribute, you must use a public method such as a getter or a setter.

public class Person {
    private int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

Inheritance: In Java, attributes can be inherited from a superclass. When a subclass inherits from a superclass, it inherits all of the superclass's attributes, including private ones. However, private attributes are not accessible directly from the subclass, so you must use public methods to access them.

Overall, attributes are an important part of object-oriented programming in Java. They define the properties of an object and are used to store data. By encapsulating attributes and providing public methods to access them, you can ensure that the internal workings of an object are hidden from the outside world.