字符串类使混乱 [英] String class make confusion

查看:80
本文介绍了字符串类使混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在Java中遇到了一个错误

Recently I just got an error in java that

Exception in thread "main" java.lang.NoSuchMethodError: main

即使我的课程只有3行代码.

Even if my class was just of 3 line of code.

public class Test{
    public static void main(String[] args){
    System.out.println("hello");
    }
}

我想知道为什么会这样,但是后来我知道有一个我尝试过的公共类String.在同一个程序包中创建.

I was wondering why this happens, but later on i get to know there was a public class String which i had tried & created in same package.

所以现在出现一个新的问题是,尽管String不是Java中定义的keyword(您可以在代码中使用),但是在这种情况下会发生什么情况

so now new question arise is what happen in this kind of situation though String is not a keyword defined in java (you can use in your code)

然后我刚刚删除了String.java&包中的String.class文件,但听起来奇怪,您也不能使用String类.

Then I just deleted String.java & String.class file from the package but it sounds odd that you could not use String class as well.

问题:java是否对我们的自定义类赋予了主要的优先权?

Question: Does java gives major priority to our custom class?

推荐答案

您的主要方法需要匹配

 public static void main(java.lang.String[] args){ ... }

如果您在使用main方法的类所在的同一包中创建自己的String类,它将变为

If you create your own String class in the same package where the class with your main method is, it will become

 public static void main(your.own.package.String[] args){ ... }

这是有效的,但由于它希望将java.lang.String[]作为参数,因此它不再允许运行时启动程序查找main方法.

which is valid, but will not allow the runtime launcher to find a main method anymore, since it expects java.lang.String[] as parameter.

默认情况下,java.lang中的类是自动导入的,因此您不需要显式的import语句-这可能会使您更加困惑.

The classes from java.lang are imported automatically by default, so you don't need an explicit import statement - that probably made it even more confusing to you.

根据经验,我会尽可能避免将自己的类命名为与Java运行时中的类相同,尤其是从java.lang中命名.

As a rule of thumb, I would avoid to name my own classes the same as classes from the Java Runtime, whenever possible - especially from java.lang.

另请参见 JLS:第7章.程序包:

一个程序包由许多编译单元(第7.3节)组成.编译单元自动访问其软件包中声明的所有类型,并且自动导入在预定义软件包java.lang 中声明的所有公共类型.

A package consists of a number of compilation units (§7.3). A compilation unit automatically has access to all types declared in its package and also automatically imports all of the public types declared in the predefined package java.lang.

这篇关于字符串类使混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆