Using Constructors in Java

I would like to know why do we need to use constructors in examples like this:http://math.hws.edu/eck/cs124/javanotes5/c5/s2.html. I think even if there are no constructors the programs mentioned in the link might run.The code is:

    public class PairOfDice
    {
    public int die1;   // Number showing on the first die.
    public int die2;   // Number showing on the second die.
    public PairOfDice() {
            // Constructor.  Rolls the dice, so that they initially
            // show some random values.
        roll();  // Call the roll() method to roll the dice.
    }

    public PairOfDice(int val1, int val2) {
            // Constructor.  Creates a pair of dice that
            // are initially showing the values val1 and val2.
        die1 = val1;  // Assign specified values 
        die2 = val2;  //            to the instance variables.
    }

    public void roll() {
            // Roll the dice by setting each of the dice to be
            // a random number between 1 and 6.
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }

} // end class PairOfDice

Is constructors used to improve the readability of the program?Could anyone help me.

4

Constructors are not used for readability. In fact, I cannot think an example in which a constructor could be user for readability.

The constructor in the example just gives an initial value to class members.

The class has two constructors:

  • One constructor doesn’t receive any parameters. This constructors randomly generates a value for each member by calling the roll() method.
  • The other constructor allows you to set the initial value of the class members.

You are right when you say the class could work without constructors, making it clear that an empty constructor is implied (inherited from Object), so in reality the class will have at least one an empty constructor.

But… as the following no-constructor alternatives show, one could soon reach to the conclusion that providing constructors makes the class more usable:

Constructor-less example 1.

Here, to ensure members have a valid state(*), they where initialized on declaration with a value of one:

public class PairOfDice {
       public int die1 = 1;
       public int die2 = 1;    
       public void roll() {
          die1 = (int)(Math.random()*6) + 1;
          die2 = (int)(Math.random()*6) + 1;
       }    
} 

Constructor-less example 2.

Here, in addition to what was done above, setters were provided to change the value of members arbitrarilly, but then it would be possible to change the values after roll, which is not desirable.

public class PairOfDice {
    public int die1=1;
    public int die2=1;    
    public void setDieOneValue(int i){die1=i;};
    public void setDieTwoValue(int i){die2=i;};
    public void roll() {
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }    
} 

Constructor-less example 3.

Here members values are randomly generated on initialization. Notice repeated code.

public class PairOfDice {
    public int die1=(int)(Math.random()*6) + 1;
    public int die2=(int)(Math.random()*6) + 1;    
    public void roll() {
        die1 = (int)(Math.random()*6) + 1;
        die2 = (int)(Math.random()*6) + 1;
    }    
} 

(*) by valid state I mean that the members have values that enforce the business rules, or runtime errors. For example, die values should be in the range 1..6 so one should garantee that they don’t have zero value at initialization. A business rule is a rule imposed by the “business”. The “bunisess” or dice rolling says that die have faces from one to six (I know theere are ther kind of dices but for the sake of simplicity we will leave them out). Having a dice throw a value of 0 would probably make the program fail. That’s what is meant by valid state.

5

The purpose of a constructor is to initialise the class’s members to a known good state. This class has two members – die1 and die2.

The class gas been given two constructors, one of which initialises the members to random numbers, the other initialises them to the values provided.

It’s not really about readability. It’s to ensure that every instance of that class is always in a valid state from the moment it’s constructed.

6

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật