Java 为什么这个组合代码不起作用?
我的程序显示错误“无法解析符号'getThePixels'”(在类Java 为什么这个组合代码不起作用?,java,methods,compiler-errors,Java,Methods,Compiler Errors,我的程序显示错误“无法解析符号'getThePixels'”(在类Main中)。代码基本上创建了一个监视器类,该类包含一个分辨率类的对象。我试图通过monitor对象访问Resolution类方法。 代码如下: 主要内容: 监视器: public class Monitor { private int height; private int width; private int length; Resolution thePixels; public M
Main
中)。代码基本上创建了一个监视器
类,该类包含一个分辨率
类的对象。我试图通过monitor对象访问Resolution
类方法。
代码如下:
主要内容:
监视器:
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);
}
}
你应该这样写你的主课
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();
}
}
不能对类主体内的对象调用方法。对
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();
}
}
你写道:
public class Main {
Resolution resolution = new Resolution(10);
Monitor monitor = new Monitor(12,13,14,resolution);
monitor.getThePixels().pix();
}
这不会运行,因为您没有运行它的main
方法:
我的意思是:
如果您使用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();
}
}
@JeroenHeier,这不是我的朋友。他就是这么说的。
public static void main(String args[])
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();
}
}