Paul Kappock
Paul Kappock

Reputation: 23

How can I print from this object? Java

I need to print the first name, last name, and salary from two employee objects but I keep getting a cannot find symbol error. What would I do to fix this?

Here is the constructor class:

public class Employee
    {
        private String firstName;
        private String lastName;
        private double monthlySalary;

        public Employee( String firstName1, String lastName1, double monthlySalary1) {
            setfirstName(firstName1);
            setlastName(lastName1);
            setmonthlySalary(monthlySalary1);
        }

        String getfirstName() {
            return firstName;
        }

        String getlastName() {
            return lastName;
        }

        double getmonthlySalary() {
            return monthlySalary;
        }

        public void setfirstName (String firstName1) {
            firstName = firstName1;
        }

        public void setlastName (String lastName1) {
            lastName = lastName1;
        }

        public void setmonthlySalary (double monthlySalary1) {
            monthlySalary = ( monthlySalary1 >= 0 ? monthlySalary1 : 0);
        }
    }

And here is what I have so far to print the objects:

public class EmployeeTest {

      public static void main(String[] args) {
            Employee a = new Employee("John", "Smith", 10000);
            Employee b = new Employee("Jane", "Smith", 11000);
            System.out.print(a.firstName1);
         }
   }

I need to be able to have it print out something along the lines of "Name: Salary:" But I am clueless as to how to make this work. Any help would be greatly appreciated.

Upvotes: 0

Views: 138

Answers (3)

Eric Stein
Eric Stein

Reputation: 13672

firstName is private, which means that it cannot be seen outside of the object/class it resides in. I suggest you try overriding the toString() method on your Employee class. That method would have access to all the private members of Employee.

Alternately, you could use getfirstName() to return the first name.

Also, this may be a typo, but there is no firstName1 in Employee - it is firstName.

Upvotes: 0

zbess
zbess

Reputation: 852

In your employee class, you need to override the toString() method.

You can try something like:

@Override
public String toString()
{
   System.out.println("Name: "+name+"Salary: "+salary);
}

Then for each of your employees, when you want to print them, just call

System.out.println(employee);

Upvotes: 1

Martin Perry
Martin Perry

Reputation: 9527

You cant print out firstName (or firstName1, because that doesnt exist in your class), because its marked as private. You should do something like this:

System.out.print(a.getfirstName())

Upvotes: 0

Related Questions