对于家庭作业,我正在研究以下三个课程。

 Class           | Extends         | Variables
 --------------------------------------------------------
 Person          | None            | firstName, lastName, streetAddress, zipCode, phone
 CollegeEmployee | Person          | ssn, salary,deptName
 Faculty         | CollegeEmployee | tenure(boolean)


我无法让Faculty构造函数正确使用超类中的数据。

 import java.util.*;
 import javax.swing.*;
 public class Faculty extends CollegeEmployee
 {
      protected String booleanFlag;
      protected boolean tenured;
      public Faculty(String firstName, String lastName, String streetAddress,
                     String zipCode, String phoneNumber, String ssn,
                     String department, double salary)
      {
           super(firstName,lastName,streetAddress,zipCode,phoneNumber,
                 department,ssn,salary);
           String booleanFlag = JOptionPane.showInputDialog(null, "Tenured (Y/N)?");
           if(booleanFlag.equals("Y"))
              tenured = true;
           else
              tenured = false;
      }
      public void setTenure(boolean tenured)
      {  this.tenured = tenured;   }
      public boolean getTenured()
      {  return tenured;  }
      public void display()
      {
          super.display();
          JOptionPane.showMessageDialog(null, "Tenured: " + tenured);
      }
 }


CollegeEmployee所属的Faculty类显示在下面。

 import java.util.*;
 import javax.swing.*;
 public class CollegeEmployee extends Person
 {
     protected String ssn;
     protected String sal;
     protected double annSalary;
     protected String department;
     public CollegeEmployee(String firstName, String lastName,
                            String streetAddress, String zipCode,
                            String phoneNumber)
     {
         super(firstName,lastName,streetAddress,zipCode,phoneNumber);
           ssn = JOptionPane.showInputDialog(null, "Enter SSN ");
          department = JOptionPane.showInputDialog(null, "Enter department: ");
          sal = JOptionPane.showInputDialog(null, "Enter salary: ");
          annSalary = Double.parseDouble(sal);
     }
     public void setFirstName(String firstName)
 {  this.firstName = firstName;  }
 public String getFirstName()
 {  return firstName;  }
     ... ETC ...  REMAINING GET/SET METHODS ELIMINATED FOR BREVITY.


我要指出的错误是参数之间的不匹配... Faculty调用了八个参数,但是CollegeEmployee只有五个。但是,我认为通过扩展CollegeEmployee扩展Person,在调用此类时,我将可以访问所有八个字段。正如已经指出的,事实并非如此。我只有Person的五个字段。因此,我显而易见的下一个问题是如何将ssn, department and salaryCollegeEmployee转换为Faculty?那是我所缺少的。我一直在研究Java教程并进行了几个小时的实验,但仍然无法获得所需的纠正方法。我是否需要通过People调用CollegeEmployee变量,然后在CollegeEmployee中实例化Faculty变量?我对要做的事情感到非常困惑,非常需要一些指导...

谢谢大家,我仔细阅读了教程中的super()关键字部分之后,我会回来的。

最佳答案

在Faculty.java中,您可以:
    超级(名字,姓氏,街道地址,邮政编码,电话号码,部门,ssn,工资);

这实际上是在调用CollegeEmployee的构造函数,该构造函数只有五个参数。这是一个编译错误。

一个类可能具有未在构造函数中设置的变量。您可以有空的构造函数,并在另一个方法中设置变量。

由于存在继承结构,因此只能通过super()设置父级变量。

10-05 18:58