You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java主类中能否存在抽象方法?含main方法的类可定义为抽象类吗

/**
 * Tests the BankAccount class and their subclasses
 * @author Saul
 *
 */
public class AccountTester 
{
    public static void main(String[] args)
    {
        SavingsAccount sa = new SavingsAccount(2,2000);
        CheckingAccount ca = new CheckingAccount(0);
        TimeDepositAccount hp = new TimeDepositAccount(10,3,15,5);
        test(sa);
        test(ca);
        test(hp);
    }
    
    public static void test(BankAccount account)
       {
            account.deposit(400);
            account.deposit(2000);
            account.withdraw(100);
            account.deposit(200);
            account.withdraw(300);
          System.out.println(account.getClass() + " before endOfMonth, the balance is: $" + account.getBalance());
          
          account.endOfMonth();
          System.out.println(account.getClass() + " after endOfMonth, the balance is: $" + account.getBalance());
       }
}

问题解答

1. 包含main方法、普通实现方法和抽象方法的类是否可以定义为抽象类?

可以,完全符合Java语法规范。
Java对抽象类的约束只有两点:

  • 类必须使用abstract关键字修饰
  • 类中只要存在未实现的抽象方法,就必须被声明为抽象类
    抽象类不限制存在已实现的普通方法、静态方法(包括main方法)、成员变量等内容,唯一的使用限制是不能直接通过new关键字实例化该类的对象。

2. 主类中是否允许存在抽象方法?

允许,前提是这个包含main方法的主类必须被声明为抽象类。
要注意的是,抽象主类的main方法可以正常执行,因为main是静态方法,不需要依赖类的实例就能运行,只是你无法直接创建该抽象主类的实例对象而已。

针对你当前的代码场景补充说明:你代码中调用的endOfMonth()是BankAccount父类的抽象方法,你只需要将BankAccount声明为抽象类,且它的所有子类(SavingsAccount/CheckingAccount/TimeDepositAccount)都实现了endOfMonth()方法,当前的测试类不需要做任何修改就能正常运行。

内容的提问来源于stack exchange,提问作者Saul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:15:02