如果你有一个Account 类,比如:
public abstract class Account{
public abstract void doSomethingAccountLike();
//more stuff
}
你可以有子类:
public class BasicAccount extends Account{
public void doSomethingAccountLike(){
//implementation specific to basic accounts
}
}
public class PremiumAccount extends Account{
public void doSomethingAccountLike(){
//implementation specific to premium accounts
}
public void doSomethingPremiumLike(){
//something that only makes sense
// in the context of a premium account
}
}
doSomethingPremiumLike() 方法仅在您有 PremiumAccount 的实例时可用,即:
public class AccountDemo{
public static void main(String[] args){
PremiumAccount premium = new PremiumAccount();
BasicAccount basic = new BasicAccount();
Account generalAccount = premium;
//valid- the compiler knows that the
//premium object is an instance of the
//premium class
premium.doSomethingPremiumLike();
//Would cause a compile error if uncommented.
//The compiler knows that basic is an instance
//of a BasicAccount, for which the method
//doSomethingPremiumLike() is undefined.
//basic.doSomethingPremiumLike();
//Would generate a compiler error if uncommented.
//Even though generalAccount actually refers to
//an object which is specifically a PremiumAccount,
//the compiler only knows that it has a reference to
//an Account object, it doesn't know that it's actually
//specifically a PremiumAccount. Since the method
// doSomethingPremiumLike() is not defined for a general
//Account, this won't compile
//generalAccount.doSomethingPremiumLike();
//All compile- all are instances of Account
//objects, and the method doSomethingAccountLike()
//is defined for all accounts.
basic.doSomethingAccountLike();
premium.doSomethingAccountLike();
generalAccount.doSomethingAccountLike();
}
}
您的问题
在我看来,您的问题很可能是在 UserClass 类中,您有一个字段 Account account。在您的构造函数中,您将new BasicAccount() 或new PremiumAccount() 分配给字段account。这很好,但是一旦你这样做了,编译器在任何给定情况下都不再知道account 字段是指PremiumAccount 实例还是BasicInstance。这意味着如果你尝试调用account.doSomethingPremiumLike(),你会得到一个编译器错误。你可以在运行时绕过这个限制:
在UserClass某处:
if(account instanceof PremiumAccount){
//if we're sure that account is actually a PremiumAccount,
//cast it to a PremiumAccount here to let the compiler know
//that doSomethingPremiumLike() can be called
((PremiumAccount)account).doSomethingPremiumLike();
}
注意:我已将您的类名称更改为以大写字母开头,这是 Java 和大多数其他 OOP 语言中的通用约定。养成遵循此约定的习惯以帮助他人阅读您的代码是件好事。