[英]How to instantiate subclasses of an abstract class?
I am stumped at the end of my program. 我在程序结束时感到困惑。 I am making a bank account java program and am having issues integrating an abstract class and a subclass together.
我正在制作一个银行帐户Java程序,并且在将抽象类和子类集成在一起时遇到问题。
public abstract class Account {
public static void main(String args[]) {
CheckingAccount Account1 = new CheckingAccount();
}
public Account() {
//
}
public class CheckingAccount extends Account {
//
}
}
I have tried the CheckingAccount
class outside and taking away the public
from the class however, then I get the error message that it cannot find the main for the Account class. 我在外面尝试了
CheckingAccount
类并从该类中夺走了public
的注意力,然后我收到错误消息,它找不到Account类的主要类。
The same error comes up as stated above if I add static
to the CheckingAccount
class. 如果将
static
添加到CheckingAccount
类,则会出现如上所述的相同错误。
You can't instantiate an instance class ( CheckingAccount
) from a static method ( main
). 您无法从静态方法(
main
)实例化实例类( CheckingAccount
)。 You have to make the inner class static
: 您必须将内部类设为
static
:
public abstract class Account {
public static void main(String args[]) {
CheckingAccount Account1 = new CheckingAccount();
}
public Account() {
//
}
public static class CheckingAccount extends Account {
//
}
}
By the way, this is a quite strange design. 顺便说一下,这是一个很奇怪的设计。 I would avoid to:
我会避免:
The problem with inner classes is - you should only use it when you absolutely know that you need it. 内部类的问题是-仅在绝对知道需要时才应使用它。 Else you would face such issues.
否则,您将面临此类问题。
So what's the issue? 那是什么问题呢? Basically an inner class instance always encloses an instance of the enclosing class.
基本上,内部类实例始终包围着该封闭类的实例。 So to access them, you need an instance of enclosing class.
因此,要访问它们,您需要一个封闭类的实例。 But, you are trying to instantiate the
CheckingAccount
class from a static
method. 但是,您正在尝试从
static
方法实例化CheckingAccount
类。 And since static
method doesn't have a reference to this
instance, that way of instantiation is illegal. 而且由于
static
方法没有this
实例的引用,所以this
实例化方法是非法的。
Problem might go if you change that instantiation to this: 如果将实例化更改为此,可能会出现问题:
public static void main(String args[]) {
CheckingAccount Account1 = new Account().new CheckingAccount();
}
But that wouldn't work either, as Account
class is abstract
. 但这也不起作用,因为
Account
类是abstract
。 So, you've should do two immediate changes here: 因此,您应该在此处立即进行两项更改:
main()
method outside the Account
class. main()
方法移到Account
类之外。 Ideally you shouldn't have main()
method in your domain classes. main()
方法。 Create a separate class for that. CheckingAccount
class outside the Account
class. CheckingAccount
类移到Account
类之外。 It will be easier for you. You can't have two public classes in one java class file. 一个Java类文件中不能有两个公共类。 And, the Java file should be named with the public class in it.
并且,Java文件应使用公共类来命名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.