Home > Back-end >  How to invoke a method on object creation?
How to invoke a method on object creation?

Time:12-21

I have the following POJO class:

public class Charity {

    private List<Donation> donations;

    private Double totalDonationAmount;

    // constructor setters etc...

    public void setTotalRaised() {

        Double totalRaised= 0.0;

        for (Donation donation: donations) {
            totalRaised = donation.getPrice();
        }
        totalDonationAmount= totalRaised;
    }

}

I can call my setTotalRaised() method in order to set the total and it works as expected. However, I want this to be calculated when the Charity object is first created.

What is the best way to do so? I know I can call the method in the constructor, but is there a better way?

CodePudding user response:

Normally, calling the method inside constructor is the only way. But, there is one other way. Don't call the method at all. In fact don't even create the field. Just create a getter method which returns total donations.

import java.util.List;

public class Charity {

    private List<Donation> donations;
    public double getTotalRaised() {
        Double totalRaised= 0.0;
        for (Donation donation: donations) {
            totalRaised = donation.getPrice();
        }
        return totalRaised;
    }

}

This is not much but it does what you need.

  • Related