gpt4 book ai didi

java - 有人可以解释一下构造函数吗?

转载 作者:行者123 更新时间:2023-12-02 00:29:14 25 4
gpt4 key购买 nike

我是 Java 新手,目前正处于编程类(class)的第四周。我们正在学习构造函数,但我似乎无法理解它。

这是我为实验室作业编写的测试类(class)。

class TestSandwich
{
public static void main (String args[])
{
Sandwich sandwich = new Sandwich();
sandwich.setMainIngredient("tuna");
sandwich.setBread("wheat");
sandwich.setPrice(4.99);
System.out.println("You have ordered a " +
sandwich.getMainIngredient() + " sandwich on " +
sandwich.getBread() + " bread, and the price is " + sandwich.getPrice());
}
}

我的任务是创建名为 Sandwich 的第二类,上面的类可以调用。我想出的如下。

public class Sandwich 
{
private String mainIngredient;
private String bread;
private double price;

public String getMainIngredient(){

return mainIngredient;
}
public String getBread(){

return bread;
}
public double getPrice(){

return price;
}
public void setMainIngredient(String ingredient){
mainIngredient = ingredient;
}
public void setBread(String bread){
bread = bread;
}
public void setPrice(double cost){
price = price;
}
}

当我运行我所拥有的内容时,它告诉我 Sandwich 类中没有 main 方法。但不应该有,所以我不明白如何消除该错误?

最佳答案

运行 TestSandwich 类而不是 Sandwich.java。任何独立 java 程序的入口点都是

public static void main (String args[])

关于java - 有人可以解释一下构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58029891/

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