Ioannis Kotsonis
Ioannis Kotsonis

Reputation: 1

Calling a method from other class, inside other method

I couldn't find a solution anywhere, so here it is:

A school project says that to use isEqual(Student) method I must use the hasSameName(Person) inside it. I have created two classes, Student and Person where boolean hasSameName(Person persons[]) compare the names inside the array and returns true if same name found and false if there's no same person.

public class Person{
    private String name,surname,address,email,phoneNumber;

    public Person(String name,String surname,String address,String email,String phoneNumber) {

        this.name = name;
        this.surname = surname;
        this.address = address;
        this.email = email;
        this.phoneNumber = phoneNumber;

    }
...
...
...

public boolean hasSameName(Person persons[]) {

        boolean flag = false;

        for(int i = 0; i<persons.length; i++) {
            for (int j = i+1; j< persons.length; j++) {
                if((persons[i].getName() == persons[j].getName() && (i!=j))){
                    flag = true;
                }
            }
        }

        if(flag == true)
            return true;
        else
            return false;

    }

The project says that boolean isEqual(Student name, Student id) should compare the name and the id values but hasSameName(Person) method must be used.

Here is the Student class:

public class Student extends Person {

    private int studentID,semester;

    public Student(String name,String surname,String address,String email,String phoneNumber,int studentID,int semester) {

        super(name,surname,address,email,phoneNumber);
        this.studentID = studentID;
        this.semester = semester;

    }
.
.
.
.

    public boolean isEqual(Student name,Student id) {
         //****************i am stuck here. I don't know how to make it work.*******************
    }

Any help will be appreciated.

Upvotes: 0

Views: 88

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19575

A school project says that to use isEqual(Student) method I must use the hasSameName(Person) inside it.

I assume that hasSameName method should have been implemented like this:

// Person.java

public boolean hasSameName(Person person) {
    if (null == person || null == person.getName())
        return false;
    return person.getName().equals(this.getName());
}

Then, as Student extends Person, you can simply call parent's methods from the child class. So, providing that the signatures of hasSameName and isEqual have been fixed, isEqual may be implemented this way:

// Student.java

public boolean isEqual(Student student) {
    return this.hasSameName(student) && this.studentID == student.getStudentID();
}

Upvotes: 1

Related Questions