错误出现在我尝试在A类中调用B类的方法,但没有主方法。

huangapple go评论122阅读模式
英文:

Error appears when i try to call a method of class B in class A without main method

问题

class B {
    void view(){
        System.out.println("in class b");
    }
}

public class A {
    {
        B obj = new B();
        obj.view();
    }
}
class B {
    void view(){
        System.out.println("in class b");
    }
}

public class A {
    public static void main(String[] args) {
        {
            B obj = new B();
            obj.view();
        }
    }
}

在第一个代码示例中,obj.view() 的行出现错误:在此标记之后需要标识符。在第二个代码示例中,将这些行放入一个代码块中,不会出现编译时错误,但会出现运行时错误:

错误:在类 A 中找不到主方法,请定义主方法:public static void main(String[] args),或者 JavaFX 应用程序类必须扩展 javafx.application.Application。

这是否意味着我不能在没有主方法的情况下运行代码?如果我需要一个主方法,那么为什么在我将其放入代码块时 Eclipse 没有显示任何错误。

英文:
class B {
	void view(){
		System.out.println("in class b");
	}
}

public class A {
	
	B obj = new B();
	obj.view();
	
}

in this code on the line obj.view there appears an error: syntax error on token view, identifier expected after this token

class B {
	void view(){
		System.out.println("in class b");
	}
}

public class A {
	{
	B obj = new B();
	obj.view();
	}
}

but when i put those line in a block like above no compile time error appears there but there appears a run time error;

Error: Main method not found in class A, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application

Does it mean that i cannot run code without main method? if i need a main method then why eclipse is not showing any error when i put it in a block

答案1

得分: 0

第一段代码失败是因为你没有将代码放在类a中的初始化块、方法或构造函数中。第二段代码将它放在了实例初始化块中,这就是错误消失的原因。

然而,由于A类是public的,并且我假设此时没有其他公共类,你需要一个应用程序的入口点。这就是为什么main方法是必要的,否则程序无法知道从哪里开始运行。因此,以下代码将有效:

class B {
    void view(){
        System.out.println("in class b");
    }
}

public class A {
    public static void main(String[] args) {
        B obj = new B();
        obj.view();
    }
}
英文:

The first piece of code fails because you don't have the code in class a in an initializer block, method or a constructor. The second piece of code puts it in an instance initializer, that's why the error has gone away.

However since the A class is public and I assume you don't have any other public classes at this point you need an entrypoint for the application. That is why the main method is necessary otherwise the program has no way to know where to start the application. Therefore this will work

class B {
void view(){
    System.out.println("in class b");
    }
}

public class A {
    public static void main(String[] args) {
        B obj = new B();
        obj.view();
    }
}

huangapple
  • 本文由 发表于 2020年8月16日 18:04:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63435529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定