Search code examples
javaobjectmethodscall

How to call a method with parameters as objects from another class java?


I am trying NOT to just call the method by inputting the values manually, but to run a method of another class from another class. I tried to find out the solution by looking at the similar questions but they did not help me in this context.

I might be wrong please forgive me, but this requirement is asking me to call a method with parameters, which I do not understand how to do.

This is the requirement:

a) Add a method payForHoliday() to the Member class. This method will simply call a method in the Website class to pay for the holiday (i.e. to record the transaction with the website). And here we have a problem because the object from the Member class doesn't keep a record of which website the member is logged into.

Class Website:

public class Website {
    private String websiteName;
    private double salesTotal;
    
    public Website(String newWebsiteName)
    {
        websiteName = newWebsiteName;
    }

    // lines omitted

    public void checkout(Member purchase, Holiday chosen) 
    {
        if (checkHitDiscount() == true)
        {
            System.out.println("Congrtulations you are eligible for 10% discount!");
            salesTotal = chosen.price;
        }
        else
        {
            System.out.println("successful completion of the transaction");
            salesTotal = chosen.price;
        }
    }

Class Member:

public class Member {
    private String email;
    public int membershipNumber;
    Holiday holiday;
    Website website;

    public Member(String newEmail, int newMembershipNumber)
    {
        email = newEmail;
        membershipNumber = newMembershipNumber;
    }

    // lines omitted

    public void payForHoliday(Member purchase, Holiday chosen) 
    {
         // This method needs to run the "checkout()" method in Website class
    }

Solution

  • The problem was that I was trying to add an object of the same class Member to call the method from the other class Website, which had a Member purchase as a parameter.

    So in order to correctly call that method, I used this code:

        public void payForHoliday(Holiday test) 
        {
           website.checkout(this, test);
        }
    
    • For pointing to the method checkout() in the Website class, I used an address(Website website) declared as an instance variable in Member class.

    • The this keyword tells the program that the parameter is the object itself, which is calling The method.

    • The test variable is placed as a parameter due to the fact that is a pointer from another class. (I changed the variable name to another name to avoid conflicts with the one in the checkout() method)