Method (computer programming) facts for kids
A method in object-oriented programming (OOP) is like a special action or ability that a computer object can perform. Think of an object as a digital "thing" in a program. This "thing" has its own information (called state data) and things it can do (called behavior).
Methods are how objects show what they can do. For example, a digital window object might have methods like `open` or `close`. The window's state, like whether it's currently open or closed, is its data. Methods let other parts of the program interact with and change an object's data.
In class-based programming, methods are defined inside a class. A class is like a blueprint for creating objects. Objects are then made based on that blueprint. One cool thing methods allow is method overriding. This means you can use the same method name, like `area`, for different types of objects. For instance, if you ask a `rectangle` object for its `area`, it uses the rectangle formula. If you ask a `circle` object for its `area`, it uses the circle formula. This makes code more flexible.
Methods also help keep an object's inner workings private. This is called encapsulation. It means other parts of the program don't need to know exactly how an object does something. They just need to know what method to call. Encapsulation and overriding are key features that make methods different from simple procedure calls.
Contents
How Methods Change: Overriding and Overloading
Method overriding and overloading are two important ways methods are different from regular computer functions. They help make object-oriented programs powerful.
Method Overriding
Overriding happens when a subclass (a more specific type of class) changes how a method from its superclass (the original, more general class) works. Imagine you have a general `Shape` class with a `findArea` method. A `Triangle` subclass might redefine `findArea` to calculate the area of a triangle. A `Circle` subclass would define it for a circle.
This idea helps treat objects like "black boxes." You don't need to know the exact details inside. You just call the method, and the object handles it. This makes code easier to manage and reuse.
Method Overloading
Method overloading is different. It means you can have multiple methods with the same name, but they do slightly different things based on the information you give them. For example, you might have a `print` method that can print a number, or print text, or print a list. The program knows which `print` method to use based on what you're trying to print.
Special Methods: Accessors, Mutators, and Managers
Methods can be grouped by what they do.
Accessor Methods
Accessor methods are used to read the data stored inside an object. They let you look at an object's information without changing it. For example, a bank account object might have a `getBalance()` method to tell you how much money is in the account.
Mutator Methods
Mutator methods are used to change the data inside an object. They let you update an object's information. For example, a bank account object might have a `deposit(amount)` method to add money or a `withdraw(amount)` method to take money out.
Manager Methods
Manager methods help create and remove objects.
- Constructors are special methods that run when an object is first created. They set up the object and give it its starting values.
- Destructors are special methods that run when an object is no longer needed and is being removed from the computer's memory. They can clean up any resources the object was using.
These methods help keep an object's data safe and organized. If a bank account class uses `getBalance()` instead of letting you directly access the balance, the way the balance is stored can change later (maybe it's fetched from a database), but your code that uses `getBalance()` won't need to change.
Constructors
A constructor is a method that automatically runs when a new object is made. It helps set up the object and gives it its first values. Constructors can take information (parameters) to help set up the object, but they usually don't give back any values.
Here's a simple example in Java:
public class Main {
String _name;
int _roll;
Main(String name, int roll) { // This is the constructor method
this._name = name;
this._roll = roll;
}
}
Destructors
A destructor is a method that automatically runs when an object is finished and removed from memory. Destructors don't usually take information or give back values. They are used to clean up things the object might have been using, like closing files or freeing up memory.
Finalizers
In some programming languages, like Java and Python, which automatically manage memory (called garbage collection), destructors are called finalizers. They do a similar job of cleaning up, but they work a bit differently because of how these languages handle memory.
Abstract Methods
An abstract method is like a promise. It's a method that has a name and what kind of information it needs, but it doesn't have any actual code inside it. It just says, "Hey, any class that uses me MUST provide the code for this method."
Abstract methods are used to define interfaces in some programming languages. They make sure that all classes that inherit from an abstract class will have certain methods.
Example
Here's an example in Java. First, an abstract class `Shape` that promises an `area` method:
abstract class Shape {
abstract int area(int h, int w); // This is an abstract method
}
Then, a `Rectangle` subclass that fulfills that promise by providing the code for `area`:
public class Rectangle extends Shape {
@Override
int area(int h, int w) {
return h * w; // Here's the code for calculating area
}
}
Special Kinds of Methods
Some methods are very specific to certain programming languages. A language might have none, some, or all of these. Often, the computer program automatically creates these methods, or a programmer can choose to define them. Most special methods can't be called directly. Instead, the computer's compiler (the program that turns your code into something the computer understands) calls them when needed.
Static Methods
Static methods are methods that belong to the class itself, not to a specific object made from that class. Think of them as general tools for the whole class. They are useful even if you haven't created any objects of that class yet.
For example, if you have a `Product` class, a static method might calculate the average price of all products, not just one specific product. A common static method in Java is `Math.max(double a, double b)`, which finds the larger of two numbers. It doesn't need a specific `Math` object to work.
Static methods are called "static" because the computer knows which one to use when it first reads your code (at compile time). This is different from regular methods, which might change what they do based on the type of object they are called on.
Examples
In Java
A common static method in Java is: `Math.max(double a, double b)` This method doesn't belong to a specific object. It gets all the information it needs from the numbers you give it.
Operator Methods
Operator methods let you change what common symbols like `+`, `-`, `*`, or `==` do when used with your own objects. This is called operator overloading.
Here's a C++ example where `==` is defined for a `Data` object:
#include <string>
class Data {
public:
bool operator<(const Data& data) const { return roll_ < data.roll_; }
bool operator==(const Data& data) const {
return name_ == data.name_ && roll_ == data.roll_;
}
private:
std::string name_;
int roll_;
};
Member Functions in C++
In C++, which is an extension of the C language, methods are often called member functions. C++ also has a special type of member function called a virtual function. Virtual functions are important for making C++ programs flexible and allowing for polymorphism. This means an object can take on many forms or behaviors.
Virtual Functions
Virtual functions are how C++ classes can show different behaviors depending on the exact type of object at the moment the program runs. Non-virtual member functions are like regular methods that don't change their behavior based on the object's type.
C++ Example:
#include <iostream>
#include <memory>
class Super {
public:
virtual ~Super() = default;
virtual void IAm() { std::cout << "I'm the super class!\n"; }
};
class Sub : public Super {
public:
void IAm() override { std::cout << "I'm the subclass!\n"; }
};
int main() {
std::unique_ptr<Super> inst1 = std::make_unique<Super>();
std::unique_ptr<Super> inst2 = std::make_unique<Sub>();
inst1->IAm(); // Calls the IAm method from the Super class.
inst2->IAm(); // Calls the IAm method from the Sub class.
}
See also
- Property (programming)
- Remote method invocation
- Subroutine, also called subprogram, routine, procedure or function