Access attributes in java

What is a good practice to access class attributes in class methods?

I always wonder about the best way to access a class attribute from a class method in Java. Could you quickly convince me about which one of the 3 solutions below (or a totally different one :P) is a good practice?

public class Test < String a; public String getA()< return this.a; >public setA(String a) < this.a = a; >// Using Getter public void display() < // Solution 1 System.out.println(this.a); // Solution 2 System.out.println(getA()); // Solution 3 System.out.println(this.getA()); >// Using Setter public void myMethod(String b, String c) < // Solution 1 this.a = b + c; // Solution 2 setA(b + c); // Solution 3 this.setA(b + c); >> 

7 Answers 7

That entirely depends on what the getters and setters are doing. If they do more than just getting and setting the value (which should be explicitly documented in the method’s Javadoc), then it would really make difference what way you’d choose from inside the class. But if they are pure Javabean like getters/setters, then I’d rather access the variable directly by either a or this.a depending on whether there’s a local variable in the scope with exactly that name.

Читайте также:  Xml parser python encoding

Personally I would just keep the getters and setters «pure» according the Javabean spec and add another getter or setter with a self-explaining method name whenever I’d like to do something more than just getting/setting the value. E.g. getAndIncrement() , getAsString() , setAsInt(String) , etc.

Matter of taste. It won’t really harm as long as you’re consistent with it throughout your coding.

If you need to create any validation in the future you’ll want a setter/getter . When you make a variable visible you brake the class encapsulation. In theory it means that your code is not so Object Oriented 😛 , but in practice you lose the ability to do a lot of code refactorings. For example, extracting a interface. And for the this call, I think its redundant, but that’s just me 🙂

The question is not about making variables visible, it is about how best to access member variables from within the class itself, i.e. access directly or use the getters and setters.

The best way to access the variables from the class itself is by accessing them directly. If you need access to a variable and solve that by creating public setters/getters then you ARE exposing internal implementation! Congratulations! Now you have locked yourself out. You cannot change the internal structure any longer because it is exposed and other classes depend on the accessor methods.

Источник

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:

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 ;

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.

Источник

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