Methods are a fundamental part of object-oriented programming. It is through them that we change and query attributes of our objects. Therefore, it is essential to understand the concept and, of course, to know how to implement methods. In today's post, in addition to addressing the conceptual part, I will also present examples of simple methods in Java and Python, remembering that this is possible in any language that supports OOP.
What are "methods"?
As mentioned briefly in the introduction of the post, methods are the means we use to read, modify and set the attributes of an object. They are always associated with a class and, in this way, can be scoped so that they can be accessed at different levels: we can define methods that can only be accessed internally in that class, methods that cannot be accessed directly, and methods that can be accessed from any part of our project.
Reasons for using methods:
We use the methods to make these accesses to objects for reasons of security and integrity of the object itself and of the application as a whole, we have to think that in a complete application, the data of the objects are stored in a database, it is not interesting (not a good practice) we allow direct access to this information, even if it is just for consultation.
What are the most used methods?
The most used methods, which have even generated ready-made solutions in several IDEs for creating them, are the methods known as "Getters and Setters", basically they are the methods used to obtain information about some attribute of the object (getters) and set the value of some attribute of the object (setters).
Now to put the knowledge into practice, nothing better than creating some methods:
Defining getters and setters in Java:
public class ExampleClass {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age= age;
}
String name = "Peter Pan";
int age = 20;
}
In this code snippet we define a class named "ExampleClass" with two attributes: name and age. In addition, we defined the getters and setters methods of this class, in this way, it is now possible to define and query the values of the class without interacting directly with the object, but with the methods.
Defining getters and setters in Python:
class Classe Example:
def __init__(self, name, age):
self._name = name
self._age = age
@name.getter
def name(self):
return self.name
@name.setter
def name(self, new_namee):
self._name = new_name
@age.getter
def age(self):
return self.age
@age.setter
def age(self, new_age):
self._age = new_age
In the code snippet above we have the same structure that we set up in Java, being applied in Python. A class named "Example" with two attributes: name and age. In addition, we define the getters and setters of this class.
Comments