Java Puzzler- What is the reason? [closed]

眉间皱痕 提交于 2019-12-04 07:06:13
public static void main(String[] args) {

Becuase you must use a java.lang.String, not your own. In your main method, the String you're using is actually the custom String that was defined, not a real java.lang.String.

Here is the code, clarified a bit:

class MyString { 

    private final String s; 

    public MyString(String s){ 
        this.s = s; 
    } 

    public String toString(){ 
        return s; 
    } 

    public static void main(MyString[] args) { // <--------- oh no!
        MyString s = new MyString("Hello world"); 
        System.out.println(s); 
    } 
}

So, the lesson that you can learn from this puzzle is: don't name your classes as other commonly used classes!

Why is it so?

Because the String[] you are using at the point is not a java.lang.String[]. It is an array of the String class that you are defining here. So your IDE (or whatever it is) correctly tells you that the main method as a valid entry point.

Lesson: don't use class names that are the same as the names of commonly used classes. It makes your code very confusing. In this case, so confusing that you have confused yourself!

Because the signature of the main method must be

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

and not

public static void main(mypackage.String[] args) { 

Usually, java.lang is implied. In this case, your personal String is used instead. Which is why you should never name your classes as those already in java.lang

The problem is that your class is named String, like the String class of Java. That's really bad, you shouldn't do that.

Because of that, when you write the declaration of main :

public static void main(String[] args) { 

String [] doesn't refer to Java String class, but to your own class, so java can't find it.

If you want java to be able to find it, you would have to write :

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

But really, it's not what you want, find an other name for your class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!