Explaining constructor & class

Hey there, so I just got through the Java course a bit and figured all the code out myself so far.

The only problem is I can’t quite wrap my head exactly around how the code works, I paste the code below here.

Can anyone just clarify a class and the constructor for me. I know it works and I made it myself… But I am not exactly sure how to use the constructor and class in a project I would do on my own for example. So please explain the logic behind a constructor & class to me :slight_smile:

public class Store {
  // instance fields
  String productType;
  int inventoryCount;
  double inventoryPrice;
  
  // constructor method
  public Store(String product, int count, double price) {
    productType = product;
    inventoryCount = count;
    inventoryPrice = price;
  }
  
  // main method
  public static void main(String[] args) {
    Store cookieShop = new Store("cookies", 12, 3.75);
    
    System.out.println(cookieShop);
    
  }
}

First, I’m no Java developer, but it appears quite similar to C# where I do have some experience, and classes are common to most languages, so I’ll try to give an answer that will be helpful.

The class you create is a new object. It can have whatever properties you wish. You could have hundreds of properties for each of your Store objects. When you define the class with instance fields you are listing the properties available for each Store when it is instantiated.

The constructor method provides an easy way to create an instance or your Store class which would be a Store object. With your constructor method you create a Store like so:

If you didn’t have a constructor method in your Store class. Creating instances would require code like this:

    Store pizzaShop = new Store();
    pizzaShop.productType = "pizza";
    pizzaShop.inventoryCount = 15;
    pizzaShop.inventoryPrice = 12.50;

Considerably more work. Hope this helps! Happy coding!

4 Likes

A constructor is called when an object or an instance is created. It is used to assign the values to the data members of the same class.

There are four basic rules to use constructor in Java

  • The name of the constructor should be the same as that of the class name.
  • A constructor cannot be declared as final, static, synchronized, or abstract type.
  • It cannot have an explicit return type.
  • A constructor can have an access modifier to control the access.

For further explanation and detailed description please visit https://tecloger.com/constructor-in-java/