Define attribute in java

Атрибуты класса в Java

Java следует объектно-ориентированному подходу к программированию, основанному на классах и объектах. Классы Java могут иметь некоторые поля и методы, которые представляют отдельные свойства и поведение/действия класса. Поля, также известные как атрибуты класса, представляют собой не что иное, как переменные, объявленные внутри класса. Например, «Студент» — это класс, а затем его номер списка, имя, раздел и т. д. могут быть атрибутами класса студенческого класса.

В этой статье представлен всесторонний обзор атрибутов класса, и для этой цели в нем объясняются следующие аспекты атрибутов класса:

  • Что такое атрибут класса
  • Как получить доступ к атрибутам класса
  • Как изменить/переопределить атрибуты класса
  • Как использовать финальное ключевое слово с атрибутами класса

Что такое атрибут класса

В Java переменная внутри класса называется атрибутом класса, а атрибуты класса также известны как поля. Давайте разберемся с концепцией атрибута класса на примере. Допустим, у нас есть класс с именем Employee, как показано в приведенном ниже фрагменте:

Здесь, в приведенном выше фрагменте empName, empId, empAge, являются атрибутами «Работник» сорт.

Как получить доступ к атрибутам класса

Доступ к атрибутам класса можно получить с помощью объекта класса. Для лучшего понимания рассмотрите приведенный ниже фрагмент кода, который раскрывает базовый синтаксис доступа к атрибуту класса:

В приведенном выше фрагменте empObj является объектом класса сотрудников и empName является атрибутом того же класса. Итак, в совокупности объект empObj используется для доступа к значению атрибута класса empName.

Пример

В приведенном ниже фрагменте кода показано, как получить доступ к атрибутам класса:

публичный статический пустота основной ( Нить [ ] аргументы ) <
Сотрудник empObj = новый Работник ( ) ;
Система . вне . печать ( empObj. empName ) ;
Система . вне . печать ( empObj. empId ) ;
Система . вне . печать ( empObj. emAge ) ;
>

Приведенный выше фрагмент сначала создает объект класса Employee, а затем получает доступ к атрибутам класса, используя объект класса Employee.

Полный код и его вывод будут такими:

Выходные данные подтверждают, что атрибуты класса успешно доступны с использованием объектов класса.

Как изменить/переопределить атрибуты класса

Мы можем изменить или переопределить атрибуты класса новыми значениями.

Пример

В этом примере мы изменим значения empName и empAge:

Нить empName = «Джон» ;
инт empId = 5 ;
инт emAge = 32 ;

публичный статический пустота основной ( Нить [ ] аргументы ) <
Сотрудник empObj = новый Работник ( ) ;
empObj. emAge = 30 ;
empObj. empName = «Джо» ;
Система . вне . печать ( «Имя сотрудника: » + empObj. empName ) ;
Система . вне . печать ( «Идентификатор сотрудника:» + empObj. empId ) ;
Система . вне . печать ( «Возраст сотрудника:» + empObj. emAge ) ;
>
>

Читайте также:  Корзина для сайта

В приведенном выше фрагменте начальные значения empId и empName равны 32 и Джо, однако мы изменили оба этих значения в основной функции:

Вывод подтвердил, что начальные значения были заменены новыми значениями.

Как использовать финальное ключевое слово с атрибутами класса

Чтобы предотвратить переопределение атрибута класса конечное ключевое слово может быть использован.

Пример

Давайте немного изменим предыдущий пример и добавим финальное ключевое слово с Атрибут класса empName:

Теперь рассмотрим приведенный ниже фрагмент, чтобы понять, что произойдет, если мы попытаемся изменить значение атрибута, объявленного с ключевым словом final:

Вывод подтверждает, что ошибка возникает, когда мы пытаемся получить доступ и изменить атрибут empName.

Как изменить конкретное значение

Если у нас есть несколько объектов класса, то изменение значения атрибута одного объекта не повлияет на значения других.

Пример

В приведенном ниже фрагменте мы создаем два объекта одного класса, и изменение значения одного атрибута в одном объекте не изменит значение этого атрибута для других объектов.

Нить empName = «Джон» ;
инт empId = 5 ;
инт emAge = 32 ;

публичный статический пустота основной ( Нить [ ] аргументы ) <
Сотрудник empObj = новый Работник ( ) ;
Сотрудник empObj1 = новый Работник ( ) ;
empObj. empName = «Джо» ;
Система . вне . печать ( «Имя сотрудника: » + empObj. empName ) ;
Система . вне . печать ( «Имя сотрудника: » + empObj1. empName ) ;
>
>

В приведенном ниже фрагменте представлен полный код вместе с выводом:

Из вывода видно, что empObj1 получает неизменное (начальное) значение, которое подтверждает, что изменение значения в одном объекте не влияет на другие.

Заключение

Переменные, созданные в классах Java, называются атрибуты или поля класса. Атрибуты класса к ним можно получить доступ с помощью объекта класса и с использованием синтаксиса точки (.). Значения атрибутов класса можно изменить, указав новое значение для атрибутов, однако конечное ключевое слово ограничивает нас в изменении значения атрибутов класса. В этой статье представлен подробный обзор атрибутов класса с помощью некоторых примеров. Для более глубокого понимания концепций описательные скриншоты также снабжены примерами.

Источник

Class Attributes in Java | Explained

Java follows the object-oriented programming approach that revolves around classes and objects. Java Classes can have some fields and methods that represent the individual properties and behavior/actions of the class. The fields also known as class attributes are nothing but the variables declared within the class. For instance, the Student is a class then the student’s roll no, name, section, etc. can be the class attributes of the Student Class.

This write-up presents a comprehensive overview of Class attributes and for this purpose, it explains the following aspects of Class Attributes:

What is a Class Attribute

In java, a variable within the class is referred as a class attribute and the class attributes are also known as fields. Let’s understand the concept of a class attribute with the help of an example. Let’s say we have a class named Employee as shown in the below-given snippet:

Читайте также:  Html onclick script function

Here in the above snippet empName, empId, empAge, are the attributes of the “Employee” class.

How to Access the Class Attributes

The attributes of the class can be accessed with the help of the class’ object. For better understanding consider the below code snippet which elaborates the basic syntax of accessing a class attribute:

In the above snippet empObj is an object of the employee class and empName is an attribute of the same class. So, collectively the object empObj is used in accessing the value of class attribute empName.

Example

The below code snippet shows how to access the class attributes:

public static void main ( String [ ] args ) {
Employee empObj = new Employee ( ) ;
System . out . println ( empObj. empName ) ;
System . out . println ( empObj. empId ) ;
System . out . println ( empObj. empAge ) ;
}

The above snippet firstly creates the object of the Employee class and afterwards it access the class attributes by using the object of the Employee class.

The complete code and its output will be:

The output verifies that the class attributes are successfully accessed by using class objects.

How to Modify/override the Class Attributes

We can modify or override the class attributes with new values.

Example

In this example we will modify the values of empName, and empAge:

String empName = «John» ;
int empId = 5 ;
int empAge = 32 ;

public static void main ( String [ ] args ) {
Employee empObj = new Employee ( ) ;
empObj. empAge = 30 ;
empObj. empName = «Joe» ;
System . out . println ( «Employee Name: » + empObj. empName ) ;
System . out . println ( «Employee ID: » + empObj. empId ) ;
System . out . println ( «Employee Age: » + empObj. empAge ) ;
}
}

In the above snippet the initial values of empId, and empName are 32 and Joe, however we modified both these values in the main function:

Output verified that the initial values have been overridden with the new values.

How to use final Keyword with Class Attributes

In order to prevent a class attribute from being overridden a final keyword can be used.

Example

Let’s modify the previous example a little bit and add the final keyword with empName class attribute:

Now, consider the below snippet to understand what will happen if we try to modify the value of attribute declared with final keyword:

The output verifies that an error occurs when we try to access and change the empName attribute.

How to Modify the Specific Value

If we have multiple objects of the class then modifying the attribute value of one object wouldn’t affect the values of others.

Example

In the below snippet, we create two objects of the same class and modifying the value of one attribute in one object wouldn’t modify the value of that attribute for other objects.

String empName = «John» ;
int empId = 5 ;
int empAge = 32 ;

Читайте также:  Install nginx php fpm mac os

public static void main ( String [ ] args ) {
Employee empObj = new Employee ( ) ;
Employee empObj1 = new Employee ( ) ;
empObj. empName = «Joe» ;
System . out . println ( «Employee Name: » + empObj. empName ) ;
System . out . println ( «Employee Name: » + empObj1. empName ) ;
}
}

The below-given snippet provides the complete code along with output:

From the output, it is clear that empObj1 gets the unchanged(initial) value which authenticates that the modifying the value in one object doesn’t affect the others.

Conclusion

The variables created within the Java classes are referred as class attributes or fields. Class attributes can be accessed with the help of object of the class and utilizing the dot (.) syntax. Values of the class attributes can be modified by specifying a new value to the attributes, however, the final keyword restricts us to modify the value of class attributes. This write-up presents a detailed overview of class attributes with the help of some examples. For a profound understanding of the concepts, descriptive screenshots are also provided with examples.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.

Источник

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:

Example

Create a class called » Main » with two attributes: x and y :

Another term for class attributes is fields.

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:

Example

Create an object called » myObj » and print the value of x :

Modify Attributes

You can also modify attribute values:

Example

Or override existing values:

Example

Change the value of x to 25:

If you don’t want the ability to override existing values, declare the attribute as final :

Example

The final keyword is useful when you want a variable to always store the same value, like PI (3.14159. ).

The final keyword is called a «modifier». You will learn more about these in the Java Modifiers Chapter.

Multiple Objects

If you create multiple objects of one class, you can change the attribute values in one object, without affecting the attribute values in the other:

Example

Change the value of x to 25 in myObj2 , and leave x in myObj1 unchanged:

Multiple Attributes

You can specify as many attributes as you want:

Example

The next chapter will teach you how to create class methods and how to access them with objects.

Источник

Оцените статью