Java class with no constructor?

前端 未结 5 1275
心在旅途
心在旅途 2021-01-27 16:46

I have this class

class Customer{
    int ID;
    Time arriveTime;
    Time serviceTime;
    Time completeTime;
    int transaction;
}

Don\'t I

相关标签:
5条回答
  • 2021-01-27 17:33

    The method that you are suggesting does not do a very good job of abstracting and separating variables. It allows them to be messed with by any code at will.

    Part of Java is OOP, or Object Oriented Programming. If you make certain parts of the class private and separated from the rest of the code, then it will limit access from other code, which helps your class follow the OO principle of encapsulation.

    Instead, I would make a constructor that fills in the fields when appropriate, such as arrive and id. I would make the variables private. Also, I would make id a static member, because it would be incremented for every new customer.

    0 讨论(0)
  • 2021-01-27 17:35

    You didn't define a constructor at all, so the default constructor will be added for you. It will, however, not set any of those fields, so you'll have to go:

    Customer c = new Customer();
    c.ID = 34
    

    And so on. A couple of things:

    • You didn't declare an access modifier, so the classes in the same package will be able to call c.ID but others won't. You might want to declare them public
    • But, it would probably be better if you created a getter and setter method instead of giving access to your fields. This way you could change the fields in the future without changing the interface
    0 讨论(0)
  • 2021-01-27 17:38

    The fields can be set from outside the class, meaning you can use another class to set the values.

    A constructor however is a more convenient way to do this indeed and can shield manipulations to the fields by another class (implemented by some programmer who might disturb the intended functionality).

    In case a class only is implemented to store a record, you can make the fields private and final and implement the appropriate getters.

    0 讨论(0)
  • 2021-01-27 17:45

    Not necessarily, as by default your attributes (values) without a visibility modifier can be set directly on instances of Customer from code in the same package.

    For example:

    Customer c = new Customer(); // default constructor 
    c.ID = 5;
    ... (etc.)
    

    More on modifier access levels here.

    0 讨论(0)
  • 2021-01-27 17:51

    Yes, you need a constructor to assign parameters to your class during object creation, or you could reference each variable individually though the instance and assign it, e.g:

     Customer c = new Customer();
     c.id = 0;
     // etc
    

    A constructor just makes this easier as you do not need to write more code than necessary.

    I do recommend using constructors to assign various values to a class instance instead of doing it manually every time you create an instance of an object.

    0 讨论(0)
提交回复
热议问题