As per our definition of Classes. A class can perform action themselves or an action can be performed on or with them. For example, we might need an action to get and set name of a product in our ‘Product’ class. Or we might need an action to calculate price of a product as well.
So how can we tell a program to perform an action? Right! We will write our action or procedure as a function for this. And what will we call this function when we wrote it as an action of a class? Yes. a method.
A method (or function) is an action that an object can perform, or an action that can be performed with or on an object.
Therefore, we can write a function getName() and setName() to get and set ‘name’ of a ‘Product’ in our program. Or we can write a function calculatePrice() to calculate price of a product for us. And we will call such functions as a ‘method’ in Object-Oriented Paradigm.
Note: Constructors are also functions. But, we don’t call or consider those a method, because, constructors already have a special meaning for us.
Some programming languages, such as Java, can have another special type of methods known as getter and setter. These are simple functions or methods that can only be used to get and set values of class properties or instance variables of an object. For example getName() and setName() above will be known as getter and setter of ‘name’ property.
A class can has zero or more methods depending upon its nature or use in our program. For example, we may and may not need calculatePrice() method in our ‘Product’ class.
Let’s move on to our next chapter and discuss another important aspect of Object-Oriented Programming. Please click on ‘Next’ to continue.