【发布时间】:2014-10-06 12:00:09
【问题描述】:
我正在编写一个简单的程序,其中我有一个由子类Customer 和Employee 继承的超类Person(它们继承了变量ID、name 和surname) .
public class Person {
int id;
String name;
String surname;
public Person() {}
public Person(int i, String n, String s) {
id = i;
name = n;
surname = s;
}
}
public class Employee extends Person implements Serializable {
String username;
String password;
String date;
int hpw;
int recordSold;
float hourPay;
public Employee() {}
public Employee(String u, String n, String s, String p, int i, int h, String d, int rSold, float hPay) {
username = u;
super.name = n;
super.surname = s;
password = p;
super.id = i;
hpw = h;
date = d;
recordSold = rSold;
hourPay = hPay;
}
}
但是问题就在这里:当我尝试通过我的主类获取变量 ID、name 和 surname 时,它们无法返回 (0,null,null)。为什么是这样?我的子类中有 get-Methods 应该返回超级变量,但它们不是。感谢您的时间和耐心。
public String getName() {
return super.name;
}
更新: 好的,所以我整理了 Employee 类构造函数中的 super(id,name,surname) 。我还删除了员工类中的所有 getter 和 setter,因为它们是从 Person 超类继承的(如果我错了,请纠正我?..)
人物超类:
public class Person {
private int id;
private String name;
private String surname;
public Person () {
}
public Person(int i, String n, String s) {
this.id = i;
this.name = n;
this.surname = s;
}
public void setID(int i) {
this.id = i;
}
public void setName(String n) {
this.name = n;
}
public void setSurname(String s) {
this.surname = s;
}
public int getID() {
return id;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
}
员工子类:
import java.io.*;
public class Employee extends Person implements Serializable {
protected String username;
protected String password;
protected String date;
protected int hpw;
protected int recordSold;
protected float hourPay;
public Employee() {
super();
}
public Employee(int i, String u, String n, String s, String p, int h, String d, int r, float hP) {
super(i,n,s);
username = u;
password = p;
date = d;
hpw = h;
recordSold = r;
hourPay = hP;
}
public void setUser(String u) {
username = u;
}
public void setPassword(String p) {
password = p;
}
public void setHWeek (int h) {
hpw = h;
}
public void setDate (String d) {
date = d;
}
public void setRSold (int r) {
recordSold = r;
}
public void setHPay (float p) {
hourPay = p;
}
public String getUser() {
return username;
}
public String getPassword() {
return password;
}
public int getHWeek() {
return hpw;
}
public String getDate() {
return date;
}
public int getRSold() {
return recordSold;
}
public float getHPay() {
return hourPay;
}
但是,当我运行主程序时,ID、name 和 surname 变量仍然为空,它们没有被超类返回。请问我错过了什么吗?谢谢
【问题讨论】:
-
请说明您是如何实例化
Employee对象的 -
您能否提供一个显示问题的可运行程序?
-
@Jens 说的,问题不在这段代码
-
@TheLostMind 他明确在Employee() 中,Java 为他调用了默认的超级构造函数。但是它仍然可以工作
-
@LionC - 我们将仅知道他是否向我们展示了他的实例化代码。
标签: java variables inheritance super