学习构造函数和对象

时间:2016-11-10 03:20:56

标签: java object constructor

我刚刚对构造函数和对象进行了一次测验(幸运的是没有测试)。

我以为我已经明白了,但我只是没有。

我们给出的问题基本上是制作一个三明治模拟器。我们被告知它有"面包" "蔬菜数量"和"肉的类型"

这里的问题确实是我不理解这一点,而不是我无法无数地阅读它。所以我正在伸出手去看看这里有人能以我能理解的方式向我解释这个问题。似乎有太多的方法可以解决我们为一个人做的事情。

这是我用它走了多远:

   import java.util.Scanner;
public class SubSandwich{
    Scanner in = new Scanner(System.in);
    private String bread;
    private int numVegs;
    private String meat;

    // Constructor
    public SubSandwich(String b, int nv, String m){
        bread = b;
        numVegs = nv;
        meat = m;
    }

    // Get the value of bread
    public String getBread(){
        return bread;
    }

    // Get the value of numVegs
    public int getNumVegs(){
        return numVegs;
    }

    // Get the value of meat
    public String getMeat(){
        return meat;
    }

    // Modify the value of bread
    public void setBread(String b){
    }

    // Modify the value of numVegs
    public void setNumVegs(int nv){

    }

    // Modify the value of meat
    public void setMeat(String m){

    }

    // Calculate and return the total cost of a sub sandwich.
    // The total cost is $5.00,
    // plus $0.50 for each vegetable.
    public double getTotalCost(){
        double totalCost = 5.00 + (getNumVegs() * .50);

        return totalCost;
    }

    public String toString(){
        System.out.println("You have a ");
    }

    public static void main(String[]args){
        SubSandwich sandwich1 = new SubSandwich("White", 2, "Chicken");


    }

    public static void printSandwich(SubSandwich sandwich1){
        System.out.println("The sandwich you ordered is " + sandwich1.getBread() + " and " + sandwich1.getNumVegs() + " vegetables, and " + sandwich1.getMeat() + ".\n That comes to $" + sandwich1.getTotalCost() + "." );
    }
}

我想知道的是'修改'到底是什么?方法为?我应该如何使用它们?

我很抱歉,如果这看起来非常模糊,我想是的,也许我只是不太了解它。这是我们给出的模板,但我已经填写了一些我认为我理解的内容。我尝试在主方法中提问和获取数据,但我不能使用非静态方法返回主方法。

我很好奇它的修改方法以及我如何访问它们是使用它们吗?

2 个答案:

答案 0 :(得分:2)

你的构造函数非常好。它将这些私有变量设置在类的顶部。

public class SubSandwich{
    private String bread;
    private int numVegs;
    private String meat;

    // Constructor
    public SubSandwich(String b, int nv, String m){
        bread = b;
        numVegs = nv;
        meat = m;
    }

现在,你不了解二传手?尝试使用bread = b替换构造函数setBread(b)。换句话说,setter方法或多或少是由构造函数完成的操作子集。 它设置值,没有什么复杂的。

现在,这不是一个真实世界三明治的模型,但如果你想换一个特定三明治的面包

SubSandwich blah = new SubSandwich("White", 2, "Chicken");
printSandwich(blah);  // prints white 
blah.setBread("wheat");
printSandwich(blah); // prints wheat 

您需要实施您的方法以反映该更新

您还可以实现toString方法,因此您只需执行

即可
System.out.println(blah);

答案 1 :(得分:1)

例如

   public void setBread(String b){
    bread = b;
    }

基本上你正在做的是修改私有变量'bread',它被设置为'b'。当您在main方法中创建SubSandwich对象时,您现在可以决定'blah'使用Flat bread而不是White bread。

SubSandwich blah = new SubSandwich("White", 2, "Chicken");
blah.setBread("Flat");