开发者

what's the point of java constructor?

开发者 https://www.devze.com 2023-04-13 00:56 出处:网络
So I\'m learning java. I\'m one month in and I just learned about constructors. But I don\'t see the whole purpose of creating one. Why and when would I ever want to开发者_开发知识库 use one? I get th

So I'm learning java. I'm one month in and I just learned about constructors. But I don't see the whole purpose of creating one. Why and when would I ever want to开发者_开发知识库 use one? I get the whole idea that it does not have a main method and you can call a constructor from your main class. Anyone can enlighten me on this topic, it would help me a great deal.


Constructors are what you use to initialize/set up the instances of your classes.

If you have an object that needs some processing before it is usable (initializing members for instance), you should do that in the constructor.

Ideally, you should never have "partially built" objects (i.e. objects that are "live", that you hold a reference to, but that are not yet usable). Without constructors, you'd be permanently creating partially built objects, and that is very error-prone. (Theory and practice don't always match, but keep that idea in mind.)


You use a constructor to create new objects. Yes, you can write Java just using static methods - but then you're really not writing object-oriented code, and you'll have a hard time using much of the standard library, either.

Most of your time you should be working with and thinking in terms of objects - and they need to be constructed before they can be used... and that's where constructors come in. They create an object, often with parameters specifying the initial state or other important information about the object.

To be honest, it's probably not worth worrying about them just yet, if you don't see the point yet. It's likely that as you learn more, you'll naturally start using objects more (maybe collections to start with, for example) and you'll get the hang of it. Rest assured, it is important to have constructors in Java, but I'm sure you'll understand why in the course of time. (Of course, if this answer has helped you to appreciate their value already, I'm glad - but if not, don't worry :)


It might seem as if you're having trouble understanding the basic concepts of objects and object-oriented programming. An explanation by example; This class represents a type of thing, namely a car:

public class Car{

    // Licence plate number. This is private, so it can
    // not be accessed directly from outside the class.
    private String hiddenRegNr = ""; 
    private static String description = "This is a car". 

    // The constructor, which sets the value of hiddenRegNr
    public Car(String regNr){
        hiddenRegNr = regNr;
    }

    // Method for reading hiddenRegNr, the only 
    // way to access it after instantiation. 
    public String getRegNr(){
        return hiddenRegNr;
    }

    // A static method. Can be used withouth instantiation.
    public static String getDesc(){
        return description;
    }
}

From some other class, you could call this class, and make instances of it; actual representations of different cars. They represent different cars, but are based on the same "model", i.e., the class Car.

Car myFirstCar = new Car("SR12345");
Car myOtherCar = new Car("XZ54321");

Now you have two different cars, with two different registration numbers. These are independent instances of the type car. They exist in memory, and may contain different values (in this case, different registration numbers).

myFirstCar.getRegNr(); // Will return SR12345
mySecondCar.getRegNr(); // will return xz54321

The first thing to notice here, is that you can only specify the registration number once per car, namely upon creation. That is the point of the constructor: It sets values, and does other stuff that needs to be done when objects (instances) are created.

Now, note the difference between getRegNr() and getDesc(): The keyword "Static" means that the second method is related directly to the class, and not to each instance. This means that:

  • Calls to getDesc() is made on the class, not an instance:

    Car.getDesc();

  • Calls to getDesc() will return the same value for all instances of the class car

  • The variable description (which is also static) will be the same for all instances of Car

  • The static method getDesc() CAN NOT access the variable hiddenRegNr, since that variable is related to a specific instance. Trying to refer to a variable in an instance from a static context (such as getDesc()) will cause an exception to be thrown. You might say that hiddenRegNr will not have been set when you call

    Car.getDesc();

because the constructor was never called, so it was never given any value.


Constructors are used to initialize a class and give parameters to a class. What is important is that they let you set the class state on creation. This allows you to use specific instances of a class with different data field values instead of relying on purely static information. Take the following example:

class Obj {
  private int state = 0;

  public Obj(int state) {
     this.state = state;
  }

  public Obj() {
     state = 1;
  }
}

Now in main (or wherever) you can have:

Obj obj1 = new Obj();
Obj obj2 = new Obj(2);

The two objects have different states (one is at state 1, the other is at state 2). If you were relying on static methods and members, the objects would share one state and would not be independent of each other.

It is also important to note that constructors (specifically the new keyword) allocate memory for a given object internally so you don't have to worry about using malloc and other memory management. So they are important in that sense as well.


It is used to create objects. Objects are the main concept in OOP, so creating them is an important step. The main class method is just an entry point to your program. If you don't create objects your program will be procedural rather than object-oriented. This is why to use a constructor.

And why to create a constructor - sometimes you need to construct an object with some required parameters. There is also a default no-argument constructor, but if you want to initialize your object with additional arguments - you create a constructor taking those arguments.


Actually constructor is needed IF you need to assign unique initial state to an instance of a class. In Java i only just realized (by a friend) that we can do this:

public class MyClass1 {
     private class MyClass2 {}
     private MyClass2 myobj2 = new MyClass2();
}

So no need for implicit constructor. But if something like follows, you need constructor.

public class MyClass1 {
     private class MyClass2 { 
         private int id_ = 0;
         public MyClass2(int id) { id_ = id; }    // how to reach this?   
     }

     private MyClass2 myobj2 = new MyClass2(1);   // (this doesn't work. Not unique)

     public MyClass1(int id)     { myobj2 = new MyClass2(id); }   // by this!
}
MyClass1 obj1 = new MyClass1(100);
MyClass1 obj2 = new MyClass1(200);


I will give you an example, imagine you have a car class.. when you call the constructor of the car class you have an car object. on this car object is possible to use diffent methods. And you could create as many as car objects as you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号