Search code examples
javaconstructorinstantiation

Can someone please explain constructors?


I am new to Java and am in the 4th week of a programming course. We are learning about constructors and I just can't seem to grasp it.

Here is my test class that was already written for the lab assignment.

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());
  }
}

My assignment is to create second class called Sandwich that the one above can call to. What I have come up with is below.

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;
    }
}

When I run what I have it tells me there is no main method in class Sandwich. There isn't supposed to be though so I don't understand how to eliminate that error?


Solution

  • Run TestSandwich class instead of Sandwich.java. The entry point of any standalone java program is

    public static void main (String args[])