Next: , Up: Packages in J.T.W. and Java   [Contents][Index]


5.1 Moving a class into a package

Consider a typical class:

class A
begin
    property int data;

    classVar int data2 = 666;

    constructor A(int d)
    begin
        data = d;
    end

    method void meth1()
    begin
        System.out.println("meth1:" + data);
    end

    method void meth2()
    begin
        System.out.println("meth2:" + data);
    end

    function void func()
    begin
        System.out.println("func:" + data2);
    end

    beginMain
        var A a1 = new A(123);
        a1.meth1(); // prints out "meth1:123"
        var A a2 = new A(456);
        a2.meth2(); // prints out "meth2:456"
        A.func(); // prints out "func:666"
    endMain
end

To move this class into a package called (for argument’s sake) pkg, you need to set the class’s visibility status from none (i.e. package visibility) to public. Also each package visible (i.e. no private or public or protected specification) class variable, function, method and property needs to have its visibility status changed from package to public if you want to be able to access these items from outside of the package. If you have more than one class in the same file, they will have to be separated into separate files as you can only have one public class per file. Also the name of the package must be declared via a package specification like so package pkg; at the top of the file before any actual class or interface definitions. Here is the same source file, ready to be put into a package:

package pkg;

public class A
begin
    public property int data;

    public classVar int data2 = 666;

    public constructor A(int d)
    begin
        data = d;
    end

    public method void meth1()
    begin
        System.out.println("meth1:" + data);
    end

    public method void meth2()
    begin
        System.out.println("meth2:" + data);
    end

    public function void func()
    begin
        System.out.println("func:" + data2);
    end

    beginMain
        var A a1 = new A(123);
        a1.meth1(); // prints out "meth1:123"
        var A a2 = new A(456);
        a2.meth2(); // prints out "meth2:456"
        A.func(); // prints out "func:666"
    endMain
end

Also the source file for the class needs to be moved into the folder ~/jtw-tutorials/pkg. To run the class, you will need to invoke the Makefile command:

make clean pkg/A.run

Next: , Up: Packages in J.T.W. and Java   [Contents][Index]