简体   繁体   中英

Call subclass methods?

So, I have this super class:

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; }
}

and its sub class

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; }
}

In another class, I have a list called 'guests' where all the guest information is stored.

How can I call the VIP subclass methods like this? (guests is a list where guest info is stored)

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
}

^ I can't do this in my code. Why not?

How am I able to do this?

Thanks

你必须先施放它:

((VIP) guest).getVIPstartDate()

You instantiated your Guests as the superclass. Without casting there is no way for the software to know you actually want VIP. There's a LOT of different ways to deal with this.

As Andronicus above me mentioned, Casting is the most obvious solution. (It's also generally what similar homework assignments are looking for) BUT you need to be careful here to verify it is actually the right subclass to cast to.

if (guest instanceof VIP){
   ((VIP) guest).getVipStartDate();
} 

此解决方案将起作用。

((VIP) guest).getVIPstartDate();

This is one of example that probably help for calling subclass 'class Manager extends Employee { . . . public void setBonus(double b) { bonus = b; } private double bonus; } There is nothing special about these methods and fields. If you have a Manager object, you can simply apply the setBonus method.

Manager boss = . . .; boss.setBonus(5000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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