如何使用抽象超类中子类的方法

时间:2014-02-21 11:24:28

标签: java inheritance subclass superclass

以下是解释我情况的基本框架代码。

这是超级抽象类:

public abstract class Person 
{   
    public void buyFood(String foodName, int payment)
    {
        System.out.println("Buy " + foodName + " and pay $" + payment + ".");
        pay(payment);
    }
}

这是超级抽象类的子类:(请注意,我删除了其他函数,例如构造函数和方法,以使帖子简短

public class Visitor extends Person
{        
    public void pay(int amount)
    {
        money_v -= amount;
        System.out.println(this.to_s() + " has got HK$" + money_v + "left.");
    }

}

我想在抽象类中使用这个public void pay(int amount)方法;但是,超级抽象类Person不接受付款(付款),因为该方法不在范围内。如何使这项工作?

感谢〜

2 个答案:

答案 0 :(得分:3)

在超类中创建pay作为抽象方法,以便子类覆盖/实现它:

abstract public void pay(int amount);

答案 1 :(得分:1)

@LarsChung:代码附在下面:

public abstract class Person 
{   
    public void buyFood(String foodName, int payment)
    {
        System.out.println("Buy " + foodName + " and pay $" + payment + ".");
        pay(payment);
    }

    public abstract void pay(int amt);
}

public class Visitor extends Person
{      

    @Override  
    public void pay(int amount)
    {
        money_v -= amount;
        System.out.println(this.to_s() + " has got HK$" + money_v + "left.");
    }

}