Reputation: 177
I've created class Person, which is extended by classes Student and Employee (which is extended by other Employee type classes). The person class looks like:
String name;
int ssn;
int age;
String gender;
String address;
String PNumber;
static int count;
//empty constructor
public Person(){
count++;
}
//print count
public static void printCount(){
System.out.println("The number of people is: "+ count);
}
//constructor with name
public Person(String name){
this.name = name;
count++;
}
/*constructor to create default person object*/
public Person(String name, int ssn, int age, String gender, String address, String PNumber)
{
this.name = name;
this.ssn = ssn;
this.age = age;
this.gender = gender;
this.address = address;
this.PNumber = PNumber;
count++;
}
I'm currently trying to create a method that will display all Persons if they're gender = "Male". I have:
//display Males
public void print(String gender){
if(this.gender.contentEquals(gender)){
//print out person objects that meet this if statement
}
}
I'm not sure how to refer to the objects (students and employees that are all persons) within the method to return them. And I also don't know how to refer to this method in the main method. I can't use Person.print, but if I use
Person james = new Person();
and then use
james.print("Males");
I'm only returning james (and the method doesn't make sense in that context).
Any help appreciated.
Upvotes: 0
Views: 5114
Reputation: 94
First, the print method should be made into a static method. It is independent of each individual Person object, so making it static will allow you to call it in the main method as
Person.print("Male");
To refer to Person objects in the print method, you will need to pass it a collection of Person objects as a parameter. You should keep all instances of Person in an array and pass that into the print method when you call it. Then the print method can be
public static void print(String gender, Person[] people) {
for(Person x : people)
if (x.gender.equals(gender))
//print the person
}
With this modification you should call it from the main method as
Person.print("Male", people);
where people is the array you keep all Person objects in.
Upvotes: 1