gpt4 book ai didi

java "redundant"包装类?

转载 作者:行者123 更新时间:2023-11-29 08:15:13 25 4
gpt4 key购买 nike

我的术语可能有误,但有人可以解释为什么我们需要在类中包装 main 方法 吗?这对我来说似乎是多余的。然后你可以再次扩展这个类,完成一个 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!");
}

此外,上述是否是构建程序的可接受方式 - 即在 main 方法中调用 Bear 类的构造函数,以及重新声明变量像这样?

刚刚开始所以对我来说有点陌生。

我的 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!");
}
}

关于java "redundant"包装类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5319020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com