为什么这段组合代码无法工作?

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

Main:

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);
    }
}

2
@JeroenHeier,它编译不了,伙计。这就是他说的。 - Chetan Kinger
3个回答

5
你应该按照以下方式编写你的主类。
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();
    }
}

您无法在类的主体内部调用对象上的方法。

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

你写道:

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();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接