简体   繁体   English

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

[英]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.

相关问题 在超类方法中使用子类成员变量? - Use subclass member variable in super class methods? 如何在子类上下文中执行从超类继承的方法? - How to execute methods inherited from super-class in the subclass context? 不覆盖抽象类中的抽象方法的具体子类 - Concrete subclass that does not override abstract methods from abstract class 如何使用子类中的属性而不是扩展抽象类中的属性? - How to use an attribute in the subclass and not the one from the extended abstract class? 抽象类-超类-子类 - Abstract class-Super Class-SubClass 为什么我们不能使用父类的引用变量来访问其子类的方法(方法在父类中不可用)? - why cant we use a reference variable of super class to access methods of its subclass(methods not available in super class)? 如何确保从子类(Java)中的方法在抽象超类中调用某些方法 - How to ensure a certain methods gets called in abstract super-class from method in sub-class (Java) 在实例化子类时从超类调用方法 - Calling methods from a super class when a subclass is instantiated 如何使用在抽象类的子类中创建的对象 - How to use a object created in a subclass of a abstract class, in the abstract class 如何使用类和子类修复 setContentView 和 super.onCreate 方法? - How to fix setContentView and super.onCreate methods using a class and subclass?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM