下面是一个计算面积和周长的例子:
# 实例化一个Square对象
> s1<-new("Square",name="s1",edges=2)
# 调用基类的getShape()函数
> getShape(r1)
Rectangle
下面是完整的R语言的代码实现:
setClass("Shape",slots=list(name="character",shape="ch
aracter"))
setClass("Ellipse",contains="Shape",slots=list(radius="numeric"),prototype=list(radius=c(1,1),shape="Ellipse"))
setClass("Circle",contains="Ellipse",slots=list(radius="numeric"),prototype=list(radius = 1,shape="Circle"))
setClass("Rectangle",contains="Shape",slots=list(edges="numeric"),prototype=list(edges=c(1,1),shape="Rectangle"))
setClass("Square",contains="Rectangle",slots=list(edges="numeric"),prototype=list(edges=1,shape="Square"))
setGeneric("getShape",function(obj,...) standardGeneric("getShape"))
setMethod("getShape","Shape",function(obj,...){
cat(obj@shape,"\n")
})
setGeneric("area",function(obj,...) standardGeneric("area"))
setMethod("area","Ellipse",function(obj,...){
cat("Ellipse Area :\n")
pi * prod(obj@radius)
})
setMethod("area","Circle",function(obj,...){
cat("Circle Area :\n")
pi*obj@radius^2
})
setMethod("area","Rectangle",function(obj,...){
cat("Rectangle Area :\n")
prod(obj@edges)
})
setMethod("area","Square",function(obj,...){
cat("Square Area :\n")
obj@edges^2
})
setGeneric("circum",function(obj,...) standardGeneric("circum"))
setMethod("circum","Ellipse",function(obj,...){
cat("Ellipse Circum :\n")
2*pi*sqrt((obj@radius[1]^2+obj@radius[2]^2)/2)
})
setMethod("circum","Circle",function(obj,...){
cat("Circle Circum :\n")
2*pi*obj@radius
})
setMethod("circum","Rectangle",function(obj,...){
cat("Rectangle Circum :\n")
2*sum(obj@edges)
})
setMethod("circum","Square",function(obj,...){
cat("Square Circum :\n")
4*obj@edges
})
e1<-new("Ellipse",name="e1",radius=c(2,5))
c1<-new("Circle",name="c1",radius=2)
r1<-new("Rectangle",name="r1",edges=c(2,5))
s1<-new("Square",name="s1",edges=2)
area(e1)
area(c1)
circum(e1)
circum(c1)
area(r1)
area(s1)
circum(r1)
circum(s1)