-3

I'm confused as to when we have to type the keyword new when we are referring to an object in java. I'm confused why in my example we didn't have to type new in the instance variables, but had to type new in the constructor. How does that work if they are referring to the same class?

public class Computer {
   private Brand brand;
   private Manufacture manufacture;

   public Computer() {
     setBrand(new Brand());
     setManufacture(new Manufacture());
Lakshmikant Deshpande
  • 708
  • 1
  • 10
  • 25
HNK123
  • 1
  • 2
  • 2
    Use `new` whenever you want a new object. – markspace Oct 19 '17 at 16:14
  • Your constructor is **exactly** equivalent to `private Brand brand = new Brand();` and `private Manufacture manufacture = new Manufacture();` – Elliott Frisch Oct 19 '17 at 16:15
  • 1
    You are **not** referring to an existing object, you are creating a new one! Up until that point brand and manufacture are unitialized and point to null. – OH GOD SPIDERS Oct 19 '17 at 16:16
  • 1
    @ElliottFrisch Well, we don't know what `setBrand()` and `setManufacture()` do. Having a full(er) source listing would help. – markspace Oct 19 '17 at 16:17
  • 2
    Possible duplicate of [When is the appropriate time to use the 'new' keyword?](https://stackoverflow.com/questions/8765351/when-is-the-appropriate-time-to-use-the-new-keyword) – d.j.brown Oct 19 '17 at 16:32

1 Answers1

1

The keyword new is used in Java to generate an instance of the specified class.

If you don't know object oriented programming, you must start there.

xalo
  • 235
  • 1
  • 9