为什么这个组合代码不起作用?

时间:2017-01-29 10:17:18

标签: java methods compiler-errors

我的程序显示错误“无法解析符号'getThePixels'”(在课程Main中)。代码基本上创建了一个Monitor类,其中包含Resolution类的对象。我试图通过监视器对象访问Resolution类方法。 以下是代码:

主:

public class Main {
    Resolution resolution = new Resolution(10);
    Monitor monitor = new Monitor(12,13,14,resolution);
    monitor.getThePixels().pix();
}

显示器:

public class Monitor {
    private int height;
    private int width;
    private int length;
    Resolution thePixels;

    public Monitor(int height, int width, int length, Resolution thePixels) {
        this.height = height;
        this.width = width;
        this.length = length;
        this.thePixels = thePixels;
    }

    public int getHeight() {
        return height;
    }

    public int getWidth() {
        return width;
    }

    public int getLength() {
        return length;
    }

    public Resolution getThePixels() {
        return thePixels;
    }
}

分辨率:

public class Resolution {
    private int pixels;

    public Resolution(int pixels) {
        this.pixels = pixels;
    }

    public void pix() {
        System.out.println("resolution is" + pixels);
    }
}

3 个答案:

答案 0 :(得分:5)

你应该像这样编写你的Main类。

public class Main {
    public static void main(String[] args) {
        Resolution resolution = new Resolution(10);
        Monitor monitor = new Monitor(12,13,14,resolution);
        monitor.getThePixels().pix();
    }
}

你不能在类体内的对象上调用方法。

答案 1 :(得分:3)

getThePixels的调用很好。但是,Java不允许在类的中间调用方法。这些类型的调用需要在方法,构造函数,匿名块或赋值中。

您似乎打算从main方法调用这些行:

public class Main {
    public static void main(String[] args) { // Here!
        Resolution resolution = new Resolution(10);
        Monitor monitor = new Monitor(12,13,14,resolution);
        monitor.getThePixels().pix();
    }
}

答案 2 :(得分:2)

你写道:

public class Main {
    Resolution resolution = new Resolution(10);
    Monitor monitor = new Monitor(12,13,14,resolution);
    monitor.getThePixels().pix();
}

这不会被运行,因为你没有main方法来运行它: 我的意思是:

public static void main(String args[])

如果使用main方法重写它,它可以工作:

public class Main {
    public static void main(String args[]){
        Resolution resolution = new Resolution(10);
        Monitor monitor = new Monitor(12,13,14,resolution);
        monitor.getThePixels().pix();
    }
}