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
相关产品推荐
相关产品推荐

