我的术语可能错了,但是有人可以解释为什么我们需要将main method
包装在一个类中吗?对我来说似乎有点多余。然后,您可以再次扩展该类并添加main
吗?
package bears;
import bears.Bear;
// what's the point of this Class here?
public class MakeBear {
public static void main(String[] args)
{
int age;
String name;
Bear MyBear = new Bear("Jim", "brown", 12, 50); // constructor
age = MyBear.getAge();
name = MyBear.getName();
System.out.println("The bear is called" + name +
" and is " + age + " years old!");
}
另外,上述方法是否可以构成程序的结构,即在
Bear
方法中调用main
类的构造函数,并像这样重新声明变量?刚开始,所以对我来说有点陌生。
如果相关的话,属于我的Bear课程的一部分:
public class Bear {
private String name;
private String colour;
private int age;
private int weight;
public Bear(String bearName, String bearColour, int bearAge, int bearWeight)
{
name = bearName;
colour = bearColour;
age = bearAge;
weight = bearWeight;
}
// get/set methods
谢谢
最佳答案
main必须在一个类中,因为Java中的所有内容都是一个类。
在您的简单示例中,主要功能通常在Bear类中。 MakeBear类是不必要的。
它将被这样重写。
public class Bear {
private String name;
private String colour;
private int age;
private int weight;
public Bear(String bearName, String bearColour, int bearAge, int bearWeight)
{
name = bearName;
colour = bearColour;
age = bearAge;
weight = bearWeight;
}
public static void main(String[] args)
{
Bear myBear = new Bear("Jim", "brown", 12, 50); // constructor
System.out.println("The bear is called" + myBear.getName() +
" and is " + myBear.getAge() + " years old!");
}
}