[英]How to use methods from a subclass in an abstract super class
Here is the basic skeleton code to explain my situation. 这是解释我的情况的基本框架代码。
This is the super abstract class: 这是超级抽象类:
public abstract class Person
{
public void buyFood(String foodName, int payment)
{
System.out.println("Buy " + foodName + " and pay $" + payment + ".");
pay(payment);
}
}
This is a sub class of the super abstract class: (note that I deleted other functions such as constructors and methods to make the post short 这是超抽象类的子类:(请注意,我删除了其他函数(例如,构造函数和方法)以简化本文。
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.");
}
}
I want to use this public void pay(int amount) method in the abstract class; 我想在抽象类中使用此public void pay(int amount)方法; however, the super abstract class Person will not accept the pay(payment) because the method is not within the scope.
但是,由于该方法不在范围之内,因此超抽象类Person将不接受pay(pay)。 How to make this work?
如何使这项工作?
Thanks~ 谢谢〜
在超类中创建pay作为抽象方法,以便子类随后覆盖/实现它:
abstract public void pay(int amount);
@LarsChung : code is attached below: @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.");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.