Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile a Java class against an interface even if none was specified

I'm teaching an intro to programming course and we're using Java. I want to help the students learn how to translate a written class specification into a working program. I will provide the written specification. It specifies the name of the class and behavior in the form of method signatures. I want the students to translate that into a working Java class.

I could provide them an interface and have them implement the interface, but that defeats part of the purpose: to read and interpret a written functional specification document. I want them to write the class from scratch. Then I want to grade their work.

My idea for checking their work is this: compile their Java class file against my own interface. If it compiles, then at least I'll know they've followed all the method contracts and I can start testing the functionality. If it doesn't compile, I'll get an error message reporting which methods were not implemented correctly.

How can I force a Java class file to be compiled against an interface even if none was originally specified in the source code?

In other words, let's say I have the following two files:

FooInterface.java

public interface FooInterface
{
    ...
}

Foo.java

public class Foo
{
    ...
}

I want to compile Foo as if it implemented FooInterface explicitly. But I don't want to have to manually edit a bunch of source code files in order to do so. How can I do it?

Edit

To address questions about the value of using a written spec vs providing the interface, here's what a hypothetical specification document looks like:

Write a class called Foo with the following methods:

oldest : ages (int[]) -> int
Given an array of ages, return the highest one.

anyAdults : ages (int[]) -> boolean
Given an array of ages, return whether any of them are 18 or older.

IMO, this has a great educational benefit. The student has to critically evaluate whether their program obeys the spec. If I provided the interface file, they could unplug their brain and simply have the compiler tell them whether or not they were following the spec. Using the compiler as a cognitive crutch is the same technique the poorer students currently (unsuccessfully) employ to balance their braces and parentheses.

like image 588
Barry Brown Avatar asked Nov 27 '22 01:11

Barry Brown


1 Answers

You could maybe do something like:

public class Bar extends Foo implements FooInterface{}

If FooInterface is fully satisfied by Foo then Bar will not have any errors.

like image 183
jonnii Avatar answered Dec 04 '22 20:12

jonnii