见过自讼 2021-05-09 19:42 采纳率: 100%
浏览 100
已采纳

关于java实现对象型数组的一个问题

具体例子:Cat类、Dog类继承于Pet类,我建立了个Pet数组,把Cat类和Dog的对象都存到了里面,最后对数组中的元素实现toString方法时只调用了Pet类中的toString,没用到Cat或Dog里的toString。请问有什么方法能调用具体子类中的toString方法吗?

[附:有关代码]

/** An interface with common collection operations.
 */
public interface Database {

    // REMEMBER THAT ALL MEMBERS OF AN INTERFACE ARE PUBLIC BY DEFAULT

    /** The default initial size of a database. */
    int STARTSIZE = 20;  // this is public, static, final by default

    /** Find out how many things are actually in the database.
     @return the number
     */
    int size();

    /** Display the items in the database on the screen.
     */
    void display();

    /** Find a particular item in the database.
     @param o the object to search for, based on equals
     @return the object if found, null otherwise
     */
    Object find(Object o);

    /** Add an item to the database, if there is room.
     @param o the object to add
     @return true if added, false otherwise
     */
    boolean add(Object o) throws Exception;

    /** Delete an item from the database, if it is there.
     @param o the object to delete
     @return the item if deleted, null otherwise
     */
    Object delete(Object o);

}



import com.sun.javaws.IconUtil;

import java.util.Arrays;

/** Class to keep track of client (Pet) information for a Veterinary
 practice. Some methods are sketched for you, but others will need
 to be added in order to implement the Database interface and
 support the P3main program and expected output. You'll also need
 to add the data members.
 */
public class Vet implements Database{

    private int startSize = STARTSIZE;
    private String vetName;
    private Pet clients[] = new Pet[startSize];

    @Override
    public String toString() {
        return "Vet{" +
                "database=" + Arrays.toString(clients) +
                '}';
    }

    public int clientsLength(){
        int cnt = 0;
        for(int i = 0;clients[i] != null;i ++)
            cnt ++;
        return cnt;
    }

    /** Find out how many things are actually in the database.
     @return the number
     */
    public int size(){

        return clientsLength();
    };

    /** Find a particular item in the database.
     @param o the object to search for, based on equals
     @return the object if found, null otherwise
     */
    public Object find(Object o){
        for(int i = 0; i < clientsLength(); i ++) {
            if (clients[i].equals(o))
                return clients[i];
        }
        return null;
    };


    /** Create a veterinary practice.
     * @param startSize the capacity for how
     * many clients they can handle
     * @param who the name of the vet practice
     */
    public Vet(int startSize, String who) {
        this.startSize = startSize;
        this.vetName = who;
    }

    /** Display the name of the Vet and all the clients, one per line,
     * on the screen. (See sample output for exact format.)
     */
    public void display() {
        System.out.println("Vet " + this.vetName + " client list:");
        for(int i = 0; i < clientsLength(); i ++){
            clients[i].information();
        }

    }


    /** Add an item to the database, if there is room.
     You are limited by the initial capacity.
     @param o the object to add (must be a Pet)
     @return true if added, false otherwise
     */
    public boolean add(Object o){
        if(!(o instanceof Pet)) return false;
        if(clientsLength() < startSize - 1){
            clients[clientsLength()] = (Pet)o;
            return true;
        }
        return false;
    }

    /** Delete an item from the database, if it is there,
     maintaining the current ordering of the list.
     @param o the object to delete
     @return the item if one is deleted, null otherwise
     */
    public Object delete(Object o) {
        for(int i = 0; i < clientsLength(); i ++){
            if(clients[i].equals(o)) {
                Pet p = clients[i];
                for (int j = i + 1; j < clientsLength(); j++)
                    clients[j - 1] = clients[j];
                clients[clientsLength() - 1] = null;
                return p;
            }
        }
        return null;
    }

    /** Compute the average weight over all clients.
     @return the average
     */
    public double averageWeight() {
        double allWeight = 0;
        for(int i = 0;i < clientsLength();i ++)
            allWeight += clients[i].getWeight();
        return allWeight / clientsLength();
    }

    /** Sort the clients. (This is complete.)
     */
    public void sort() {
        Arrays.sort(this.clients, 0, this.size());
    }

}

/**
 *  This program does not test everything your class
 *  system is supposed to do, so you might want to write
 *  some of your own tests.
 */



public class P3main{

    /** Main driver method.
     * @param args the arguments (not used)
     */
    public static void main(String[] args) {
        Vet avet = new Vet(50, "Pets R Us");
        Pet p;

        p = new Pet("Rudolph", "Santa Claus", 350);
        p.visit(1);
        avet.add(p);
        avet.add(new Pet("Tweetie Bird", "Looney Tunes", 1.75));
        System.out.println("visit1: " + p.visit(1));
        System.out.println();
        show(avet);

        p = new Cat("Tiger", "Some Body", 8);
        avet.add(p);
        System.out.println("visit0: " + p.visit(0));

        Cat c = new Cat("Sylvester", "Looney Tunes", 15.5);
        System.out.println("inside visit1: " + c.visit(1));
        c.goOutside();
        System.out.println("outside visit1: " + c.visit(1));
        System.out.println("c is " + c);
        avet.add(c);

        System.out.println();
        show(avet);

        Dog d = new Dog("Fido", "Some Body", 32.2, "medium");
        System.out.println("med visit3: " + d.visit(3));
        avet.add(d);

        p = new Dog("Dino", "Flintstones", 150, "large");
        avet.add(p);
        System.out.println("lg visit3: " + p.visit(3));
        System.out.println();
        show(avet);

        avet.add(new Dog("Benji", "Joe Camp", 10, "small"));
        p = new Cat("Tony", "Kellogg", 20);
        avet.add(p);
        System.out.println();
        show(avet);

        System.out.println("\na few more tests...");
        System.out.println("find p: " + avet.find(p));
        p = (Pet) avet.find(new Pet("Tweetie Bird", "Looney Tunes", 1.5));
        System.out.println("Tweetie 5 shots: " + p.visit(5));
        System.out.println("found Tweetie: " + p);

        System.out.println("find Fido: "
                + avet.find(new Dog("Fido", "some body", 32.2, "medium")));

        System.out.println("adding string to Vet: " + avet.add("not a pet"));
        System.out.println("deleting string: " + avet.delete("just a string"));

        System.out.println();
        System.out.println("\ndeleting pets:");
        System.out.println(avet.delete(p));
        System.out.println(avet.delete(d));
        System.out.println(avet.delete(c));
        show(avet);

        avet.add(new Pet("Happy", "Some Body", 13.5));
        avet.sort();
        System.out.println("\nafter sorting:");
        show(avet);
    }

    /** Output the current state of things to the screen.
     *  @param myvet the vet records to display
     */
    public static void show(Vet myvet) {
        System.out.println("--- Vet has " + myvet.size() + " clients");
        myvet.display();
        System.out.println(">> average client weight: " + myvet.averageWeight());
    }
}


/* Here is the result of running the program:

visit1: 115.0

--- Vet has 2 clients
Vet Pets R Us client list:
Rudolph (owner Santa Claus) 350.0 lbs, $115.00 avg cost/visit
Tweetie Bird (owner Looney Tunes) 1.75 lbs, $0.00 avg cost/visit
>> average client weight: 175.875
visit0: 105.0
inside visit1: 135.0
outside visit1: 165.0
c is outside cat Sylvester (owner Looney Tunes) 15.5 lbs, $150.00 avg cost/visit

--- Vet has 4 clients
Vet Pets R Us client list:
Rudolph (owner Santa Claus) 350.0 lbs, $115.00 avg cost/visit
Tweetie Bird (owner Looney Tunes) 1.75 lbs, $0.00 avg cost/visit
inside cat Tiger (owner Some Body) 8.0 lbs, $105.00 avg cost/visit
outside cat Sylvester (owner Looney Tunes) 15.5 lbs, $150.00 avg cost/visit
>> average client weight: 93.8125
med visit3: 197.5
lg visit3: 205.0

--- Vet has 6 clients
Vet Pets R Us client list:
Rudolph (owner Santa Claus) 350.0 lbs, $115.00 avg cost/visit
Tweetie Bird (owner Looney Tunes) 1.75 lbs, $0.00 avg cost/visit
inside cat Tiger (owner Some Body) 8.0 lbs, $105.00 avg cost/visit
outside cat Sylvester (owner Looney Tunes) 15.5 lbs, $150.00 avg cost/visit
medium dog Fido (owner Some Body) 32.2 lbs, $197.50 avg cost/visit
large dog Dino (owner Flintstones) 150.0 lbs, $205.00 avg cost/visit
>> average client weight: 92.90833333333335

--- Vet has 8 clients
Vet Pets R Us client list:
Rudolph (owner Santa Claus) 350.0 lbs, $115.00 avg cost/visit
Tweetie Bird (owner Looney Tunes) 1.75 lbs, $0.00 avg cost/visit
inside cat Tiger (owner Some Body) 8.0 lbs, $105.00 avg cost/visit
outside cat Sylvester (owner Looney Tunes) 15.5 lbs, $150.00 avg cost/visit
medium dog Fido (owner Some Body) 32.2 lbs, $197.50 avg cost/visit
large dog Dino (owner Flintstones) 150.0 lbs, $205.00 avg cost/visit
small dog Benji (owner Joe Camp) 10.0 lbs, $0.00 avg cost/visit
inside cat Tony (owner Kellogg) 20.0 lbs, $0.00 avg cost/visit
>> average client weight: 73.43125

a few more tests...
find p: inside cat Tony (owner Kellogg) 20.0 lbs, $0.00 avg cost/visit
Tweetie 5 shots: 235.0
found Tweetie: Tweetie Bird (owner Looney Tunes) 1.75 lbs, $235.00 avg cost/visit
find Fido: medium dog Fido (owner Some Body) 32.2 lbs, $197.50 avg cost/visit
adding string to Vet: false
deleting string: null


deleting pets:
Tweetie Bird (owner Looney Tunes) 1.75 lbs, $235.00 avg cost/visit
medium dog Fido (owner Some Body) 32.2 lbs, $197.50 avg cost/visit
outside cat Sylvester (owner Looney Tunes) 15.5 lbs, $150.00 avg cost/visit
--- Vet has 5 clients
Vet Pets R Us client list:
Rudolph (owner Santa Claus) 350.0 lbs, $115.00 avg cost/visit
inside cat Tiger (owner Some Body) 8.0 lbs, $105.00 avg cost/visit
large dog Dino (owner Flintstones) 150.0 lbs, $205.00 avg cost/visit
small dog Benji (owner Joe Camp) 10.0 lbs, $0.00 avg cost/visit
inside cat Tony (owner Kellogg) 20.0 lbs, $0.00 avg cost/visit
>> average client weight: 107.6

after sorting:
--- Vet has 6 clients
Vet Pets R Us client list:
large dog Dino (owner Flintstones) 150.0 lbs, $205.00 avg cost/visit
small dog Benji (owner Joe Camp) 10.0 lbs, $0.00 avg cost/visit
inside cat Tony (owner Kellogg) 20.0 lbs, $0.00 avg cost/visit
Rudolph (owner Santa Claus) 350.0 lbs, $115.00 avg cost/visit
Happy (owner Some Body) 13.5 lbs, $0.00 avg cost/visit
inside cat Tiger (owner Some Body) 8.0 lbs, $105.00 avg cost/visit
>> average client weight: 91.91666666666667

*/
import java.text.DecimalFormat;
import java.util.Objects;

/** This is a class to define Pet objects. Pets should be compared
 according to their owner's names, ignoring capitalization. Ties
 should be broken based on the pet's name, ignoring capitalization.

 Your job is to add the necessary data and methods to support the
 P3main program, as well as the related classes in this system. Some
 required methods are noted below with comments, but these are not the
 only things you will need.
 */



public class Pet implements Comparable {

    /** Handy for formatting. */
    private static DecimalFormat money = new DecimalFormat("0.00");

    /* The access specifiers for these variables must not be changed! */

    private String name;
    private String owner;
    private double weight;
    private int visitTimes;
    private double allCost;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Pet pet = (Pet) o;
        return name.equalsIgnoreCase(pet.name) &&
                owner.equalsIgnoreCase(pet.owner);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, owner);
    }

    /** Create a Pet object, initializing data members.
     *  @param pname the Pet's name
     *  @param oname the owner's name
     *  @param wt the weight of the pet
     */
    public Pet(String pname, String oname, double wt) {
        this.name = pname;
        this.owner = oname;
        this.weight = wt;
    }

    @Override
    public String toString() {
        return this.name + " (owner " + this.owner + ") " + this.weight
                + " lbs, $" + money.format(this.avgCost()) + " avg cost/visit  ";
    }

    /** The Pet is visiting the vet, and will be charged accordingly.
     *  The base cost for a visit is $85.00, and $30/shot is added.
     *  @param shots the number of shots the pet is getting
     *  @return the entire cost for this particular visit
     */
    public double visit(int shots) {
        double cost = 0;
        cost = 85 + 30 * shots;
        visitTimes ++;
        allCost += cost;
        return cost;
    }

    public void changeAllCost(double allCost){
        this.allCost = allCost;
    }

    public double getAllCost(){
        return this.allCost;
    }

    /** Determine the average cost per visit for this pet.
     *  @return that cost, or 0 if no visits have occurred yet
     */
    public double avgCost() {
        if(allCost == 0) return 0;
        return allCost / visitTimes;
    }

    public double getWeight(){
        return this.weight;
    }

    public void information(){
        System.out.println(name + "(owner " + owner + ")" + weight + "lbs,$" + avgCost() + "avg cost/vist");
    }

    @Override
    public int compareTo(Object o) {
        return 0;
    }
}



import java.util.Objects;

public class Dog extends Pet{
    private String body;

    @Override
    public String toString() {
        return body + " dog " + super.toString();
    }

    public Dog(String name, String owner, double weight, String body){
        super(name,owner,weight);
        this.body = body;
    }

    public double visit(int shots){
        double cost = super.visit(shots);
        double cost2 = 0;
        cost2 += 15;
        if(body.equals("medium")) cost2 += 2.5 * shots;
        else if(body.equals("large")) cost2 += 5 * shots;
        cost += cost2;
        double allCost = getAllCost();
        changeAllCost(allCost + cost2);
        return cost;
    }
}



public class Cat extends Pet{
    private boolean isInside = true;

    public Cat(String name,String owner,double weight){

        super(name,owner,weight);
    }

    public void goOutside(){
        this.isInside = false;
    }

    @Override
    public String toString() {
        if(isInside) return "inside cat " + super.toString();
        return "outside cat " + super.toString();
    }

    public double visit(int shots){
        double cost = super.visit(shots);
        double allCost,cost2 = 0;
        cost2 += 20;
        if(!isInside) cost2 += 30;
        cost += cost2;
        allCost = getAllCost() + cost2;
        changeAllCost(allCost);
        return cost;
    }
}

问题出在p3main类中的delete操作,输出时只会调用Pet类toString

  • 写回答

8条回答 默认 最新

  • 关注

    你的数组

    赋值的是Cat对象就会调用Cat的toString方法,toString方法要在Cat里面重写

    赋值的是Dog对象就会调用Dog的toString方法,toString方法要在Dog里面重写

    赋值的是Pet对象就会调用Pet的toString方法,toString方法要在Pet里面重写

    不可能出现你说的这种情况

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装