不能使用其他包类的方法而不使其静态

时间:2018-02-25 14:42:33

标签: java

我的Eclipse项目中有两个文件。它们是:PageRankSparse.java和PageRank.java。 PageRank.java已经完成,我现在希望在PageRankSparse.java中使用它的一些方法。我尝试使用其中一个subtract(),但得到了这个编译错误消息:

Cannot make a static reference to the non-static method subtract(double[], double[]) from the type PageRank.

出现此错误的原因是什么?请注意,运行PageRank.java时我从未遇到此错误。这是代码:

public class PageRank {

    //Omitted declared constants for simplicity    

    public PageRank( String filename ) {

        int noOfDocs = readDocs( filename );
        NUMBER_OF_DOCS = noOfDocs;
        initiateProbabilityMatrix( noOfDocs );
        iterate( noOfDocs, 100 );
    }

    double[] subtract(double[] x, double[] y){
        if( !(x.length == y.length) ){
            throw new RuntimeException("vector dimensions must match in subtract()");
        }
        double[] z = new double[x.length];
        for(int i=0; i<x.length; i++){
            z[i] = x[i] - y[i];
        }
        return z;
    }


    public static void main( String[] args ) {
        if ( args.length != 1 ) {
            System.err.println( "Please give the name of the link file" );
        }
        else {
            new PageRank( args[0] );
        }
    }
}

PageRankSparse.java:

public class PageRankSparse {
    //Omitted declared constants for simplicity

    public PageRankSparse( String filename ) {
        int noOfDocs = readDocs( filename );
        NUMBER_OF_DOCS = noOfDocs;
        iterate( noOfDocs, 1000 );
    }

    void iterate( int numberOfDocs, int maxIterations ) {
            double[] a = new double[numberOfDocs];
            a[0] = 1;
            double[] aNew; 
            double[] diff;
            int i;
            for(i = 0; i<maxIterations; i++) {
                aNew = vDotHashMap(a, link);
                diff = PageRank.subtract(aNew, a); // ERROR IS HERE
                // the rest is not implemented
            }

    }

    public static void main( String[] args ) {
    if ( args.length != 1 ) {
        System.err.println( "Please give the name of the link file" );
    }
    else {
        new PageRankSparse( args[0] );
    }
    }
}

1 个答案:

答案 0 :(得分:1)

很清楚。如果不创建新实例,则无法在类外调用非静态方法。

如果您希望直接调用该方法,可以在方法中添加static关键字:

static double[] subtract(double[] x, double[] y)