Java class with no constructor?

前端 未结 5 1429
心在旅途
心在旅途 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: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

提交回复
热议问题