gpt4 book ai didi

java - 调用子类方法?

转载 作者:行者123 更新时间:2023-12-01 07:44:54 25 4
gpt4 key购买 nike

所以,我有这个 super 类:

public class Guest {

private int id;
private String firstName;
private String lastName;
private LocalDate joinDate;

public Guest(int id, String firstName, String lastName, LocalDate joinDate){

this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.joinDate = joinDate;

}
public int getID(){ return id; }
public String getFirstName(){ return firstName; }
public String getLastName(){ return lastName; }
public LocalDate getJoinDate(){ return joinDate; }
}

及其子类

public class VIP extends Guest{

private LocalDate VIPstartDate;
private LocalDate VIPexpiryDate;

public VIP(int id, String firstName, String lastName, LocalDate joinDate, LocalDate VIPstartDate, LocalDate VIPexpiryDate){

super(id, firstName, lastName, joinDate);

this.VIPstartDate = VIPstartDate;
this.VIPexpiryDate = VIPexpiryDate;
}
public LocalDate getVIPstartDate(){ return VIPstartDate; }
public LocalDate getVIPexpiryDate(){ return VIPexpiryDate; }
}

在另一个类(class)中,我有一个名为“客人”的列表,其中存储了所有客人信息。

如何调用这样的 VIP 子类方法? (guests是存储客人信息的列表)

for (Guest guest : guests){
guest.getid() // so this calls from the super class - this works
guest.getVIPstartDate() // this is meant to call from sub class - this doesn't work
}

^ 我无法在我的代码中执行此操作。为什么不呢?

我怎样才能做到这一点?

谢谢

最佳答案

这个解决方案可行。

((VIP) guest).getVIPstartDate();

关于java - 调用子类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55176235/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com