Encapsulation, which is the bundling of data and the methods that operate on that data into a single unit. In R, you can achieve encapsulation by using S3 or S4 classes. Here's an example using S3 classes:
```r
# Create an S3 class
circle <- structure(
list(radius = 1),
class = "circle"
)
# Create a method for the S3 class
print.circle <- function(x, ...) {
cat("A circle with radius", x$radius, "\n")
}
# Call the method
print(circle)
```
abstraction, which involves hiding the complex details and showing only the necessary features of an object. In R, you can achieve abstraction through the creation of functions and classes that expose only the necessary functionality to the user.
```r
# Create a function to calculate area of a circle
calculate_area <- function(radius) {
return(pi * radius^2)
}
# Call the function
area <- calculate_area(3)
print(area)
```
Polymorphism, which allows objects of different types to be treated as objects of a single type. In R, you can achieve polymorphism through function overloading or S4 classes.
```r
# Function overloading example
add_numbers <- function(x, y) {
return(x + y)
}
# Overload the add_numbers function for concatenating strings
add_numbers <- function(x, y) {
return(paste(x, y))
}
# Call the overloaded functions
result1 <- add_numbers(1, 2)
print(result1) # Output: 3
result2 <- add_numbers("Hello", "World")
print(result2) # Output: "Hello World"
```
I hope these examples help you understand encapsulation, abstraction, and polymorphism in the context of R programming language! Let me know if you have any other questions.

No comments:
Post a Comment