Creating Generic Method

Let’s create a class bank and let’s try to create our own display() method that will use the print() method and will display the content of the class in the format specified by us.

For doing this we first have to create a generic display() function that will use the UseMethod function.

R




display <- function(obj){
    UseMethod("print")
}


After creating the generic display function let’s create the display function for our class bank.

R




print.bank<-function(obj)
{
    cat("Name is ", obj$name, "\n")
    cat(obj$account_no, " is the Acc no of the holder\n ")
    cat(obj$saving, " is the amount of saving in the account \n ")
    cat(obj$withdrawn, " is the withdrawn amount\n")
}


Now, let’s see the output given by this function

R




x <- list(name ="Arjun", account_no = 1234,
        saving = 1500, withdrawn = 234)
class(x)<-"bank"
 
display <- function(obj){
    UseMethod("print")
}
 
print.bank<-function(obj)
{
    cat("Name is ", obj$name, "\n")
    cat(obj$account_no, " is the Acc no of the holder\n ")
    cat(obj$saving, " is the amount of saving in the account \n ")
    cat(obj$withdrawn, " is the withdrawn amount\n")
}
 
display(x)


Output:

Name is  Arjun 
1234  is the Acc no of the holder
 1500  is the amount of saving in the account 
 234  is the withdrawn amount


Polymorphism in R Programming

R language is evolving and it implements parametric polymorphism, which means that methods in R refer to functions, not classes. Parametric polymorphism primarily lets you define a generic method or function for types of objects you haven’t yet defined and may never do. This means that one can use the same name for several functions with different sets of arguments and from various classes. R’s method call mechanism is generics which allows registering certain names to be treated as methods in R, and they act as dispatchers. 

Similar Reads

Generic Functions

Polymorphism in R can be obtained by the generics. It allows certain names to be treated as methods and they act as dispatchers. Let’s understand with the help of plot() function and summary function. In R programming the plot() and summary() functions return different results depending on the objects being passed to them and that’s why they are generic functions that implement polymorphism....

plot() in R

plot() is one of the generic functions that implement polymorphism in R. It produces a different graph if it is given a vector, a factor, a data frame, etc. But have you ever wondered how does the class of vectors or factors determine the method used for plotting?  Let’s see the code for the plot function....

summary() in R

...

Creating Generic Method

...

Contact Us