[英]Why is my method undefined for the type object?
I'm not sure why Eclipse is giving me this error:我不知道为什么 Eclipse 给我这个错误:
The method
listen()
is undefined for the typeObject
未定义Object
类型的方法listen()
What simple mistake am I making?我犯了什么简单的错误? Also, is my code the right way to write a main
method which instantiates an EchoServer0
object and calls its listen
method?另外,我的代码是否是编写实例化EchoServer0
对象并调用其listen
方法的main
方法的正确方法?
public class EchoServer0 {
public void listen() {
ServerSocket socket = null;
try{
socket = new ServerSocket(2013);
System.out.println("Opened server socket");
socket.setSoTimeout(2000);
socket.accept();
socket.close();
}
catch (SocketTimeoutException ste){
System.out.println("Timed out after " + 2000 + " ms");
}
catch (Exception e){
System.out.println(e.getClass().getName()+" at server: " + e.getMessage());
}
}
public static void main(String[] args) {
Object EchoServer0;
EchoServer0.listen();
}
}
Change your main to:将您的主要更改为:
public static void main(String[] args) {
EchoServer echoServer = new EchoServer();
echoServer.listen();
}
When you declare Object EchoServer0;
当您声明Object EchoServer0;
you have a few mistakes.你有几个错误。
new
.您还需要使用new
创建它的一个实例。Try this.试试这个。
public static void main(String[] args) {
EchoServer0 myServer;
myServer = new EchoServer0();
myServer.listen();
}
What you were trying to do was declaring a variable of type Object
, not creating anything for that variable to reference, then trying to call a method that didn't exist (in the class Object
) on an object that hadn't been created.您试图做的是声明一个Object
类型的变量,而不是为该变量创建任何要引用的变量,然后尝试在尚未创建的Object
上调用不存在的方法(在Object
类中)。 It was never going to work.它永远不会奏效。
The line线
Object EchoServer0;
says that you are allocating an Object
named EchoServer0
.说你正在分配一个名为EchoServer0
的Object
。 This has nothing to do with the class EchoServer0
.这与EchoServer0
类无关。 Furthermore, the object is not initialized, so EchoServer0
is null
.此外,该对象未初始化,因此EchoServer0
为null
。 Classes and identifiers have separate namespaces.类和标识符具有单独的命名空间。 This will actually compile:这将实际编译:
String String = "abc"; // My use of String String was deliberate.
Please keep to the Java naming standards: classes begin with a capital letter, identifiers begin with a small letter, constants and enum
s are all-capitals.请遵守 Java 命名标准:类以大写字母开头,标识符以小写字母开头,常量和enum
都是大写字母。
public final String ME = "Eric Jablow";
public final double GAMMA = 0.5772;
public enum Color { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET}
public COLOR background = Color.RED;
It should be like that应该是这样
public static void main(String[] args) {
EchoServer0 e = new EchoServer0();
// TODO Auto-generated method stub
e.listen();
}
Your variable of type Object
truly doesn't have such a method, but the type EchoServer0
you define above certainly has.你的Object
类型的变量确实没有这样的方法,但是你上面定义的类型EchoServer0
肯定有。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.