简体   繁体   English

当我们有两个具有相同属性的类时,如何在 Java 中为参数化构造函数创建对象?

[英]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.我有 class 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.我还有第二个 class 教授,他有名字、姓氏和大学。 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.在主要的 class 中,我创建了两个对象。

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?它向我显示一个错误:字符串无法转换为学生,有人可以解释为什么会这样,我应该如何解决这个问题?

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.您需要先命名实例,然后指定要在点后调用的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM