Search code examples
javacompositionsuperclass

How to use composition from another class to set Name?


I have some of the code here. I am trying to use one class to reference another so I may obtain the first name of the person. I want the firstName in main class to work but IDE mentions the variable isn't found. Will replacing 'first' with 'firstName' work?

Main class:

public BasePlusCommissionEmployee( String first, String last, 
            String ssn, double sales, double rate, double salary) {


        cE = new CommissionEmployee( first, last, ssn, sales, rate );
        setBaseSalary( salary );
    }

public void setFirstName(String firstName) {
        // Trying to get this to work...
        cE.setFirstName(first);
    }

SubClass:

private String firstName;
public void setFirstName( String first )
    {
        firstName = first;
    }    

Solution

  • Will replacing 'first' with 'firstName' work?

    Yes.

    public void setFirstName(String firstName) {
        // Trying to get this to work...
        cE.setFirstName(first);
    }
    

    firstName is local variable to this method and a variable with name first is not defined within it.

    So, if you use first, it will be compilation error.