Domanda

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.

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.

The same error comes up as stated above if I add static to the CheckingAccount class.

È stato utile?

Soluzione

You can't instantiate an instance class (CheckingAccount) from a static method (main). You have to make the inner class 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:

  • mix your main method with your classes, just make a new separated Account class instead
  • declare an inner class as an extends of the container class, use two classes (in two different classes) instead.

Altri suggerimenti

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. And since static method doesn't have a reference to this instance, that way of instantiation is illegal.

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. So, you've should do two immediate changes here:

  1. Move the main() method outside the Account class. Ideally you shouldn't have main() method in your domain classes. Create a separate class for that.
  2. Move CheckingAccount class outside the Account class. It will be easier for you.

You can't have two public classes in one java class file. And, the Java file should be named with the public class in it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top