Menu
CoddyTech

S3 Object Construction

Lesson 32 of 48 in Coddy's R for Java Developers course.

Java classes declare fields, constructors and instance behavior. An R S3 object can simply be a list with a class attribute and external generic methods. Constructor functions should establish the representation because a class tag alone validates no fields. Preserve the public object shape across supporting files.

Java

import java.util.*;
import java.util.function.*;
import java.util.regex.*;
public class Main {
static class Item {int n; Item(int n){this.n=n;}}
public static void main(String[] args) throws Exception {
Item a=new Item(2),b=new Item(5); System.out.println(a.n+b.n);
}
}

R

new_lamp <- function() structure(list(on=FALSE),class="lamp")
a<-new_lamp();b<-new_lamp();a$on<-TRUE
cat(b$on,"\n",sep="")

An S3 class label does not validate every field automatically.

challenge icon

Challenge

Easy

Implement new_meter(value) returning an S3 object with class meter and one numeric list member value. Implement read_meter(x) returning its value. Input is one number.

Keep the declared public API. The visible locked driver checks it directly as well as printing solve(lines). Inputs satisfy the stated contract; all arithmetic is small and finite.

Your code goes in Meter.R and Exercise.R. main.R sources dependencies in order and holds the supplied input/output code; it cannot be edited.

Try it yourself

source("Meter.R")
source("Exercise.R")
x<-new_meter(17);stopifnot(inherits(x,"meter"),is.list(x),identical(x$value,17),identical(read_meter(x),17))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in R for Java Developers

Practice on your own: Online R compiler