Skip to content
Advertisement

How to create objects for parameterized constructors in Java, when we have two classes with the same attributes?

I have class Student, that has first name, last name and age, and a method to print the name and the age of the student.

public class Student {
       private String firstName;
       private String LastName;
       private int age;
}
Student() {}
public Student(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}
public void printInfoStudent(){
System.out.println("Student: " + firstName + " " + lastName + ", " + age);
}

And I have a second class Professor, that has first name, last name, and university. And I have a method to print the info about the professor.

public class Professor {
       private Student firstName;
       private Student lastName;
       private String uni;
}
Professor() {
    
}

public Professor(Student firstName, Student lastName, String uni) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.uni = uni;
}
public Student getFirstName() {
    return firstName;
}

public void setFirstName(Student firstName) {
    this.firstName = firstName;
}

public Student getLastName() {
    return lastName;
}

public void setLastName(Student lastName) {
    this.lastName = lastName;
}

public String getUni() {
    return uni;
}

public void setUni(String uni) {
    this.uni = uni;
}
public void printInfo(){
System.out.println("Professor: " + firstName + " " + lastName + ", uni: " + university);
}

And in the main class I create two objects.

Student s = new Student("John", "John", 24);
Professor p = new Professor("Johnny", "Johnny", "Oxford"); 

printInfo.p();
printInfoStudent.s();

And it’s showing me an error: String cannot be converted to Student, can someone explain why is that, and how should I fix this?

Advertisement

Answer

You’ve created the objects properly but are not calling their functions properly.

Student s = new Student("John", "John", 24);
Professor p = new Professor("Johnny", "Johnny", "Oxford"); 

p.printInfo()
s.printInfoStudent();

You need to name the instance first then specify the method inside to call after the dot.

Advertisement