0

H, beginner here.

I have an abstract class called 'Command', which has several subclasses that extend it, all of which are commands and use the variables and some methods in 'Command'. In a seperate class (that doesn't extend Command), there is some code that invokes these several classes whenever the user does so. The Command class has some variables that I'd like to read from (with getter methods) within the seperate class.

public abstract class Command {

    private String variableName;

    public String getCurrentVariableName() {
        return variableName;
    }
}



public class SeperateClass {

//  rest of code

System.out.println(command.getCurrentVariableName());

}

Creating an object of the class doesn't work because I can't instantiate an abstract class. I'm guessing I could instantiate one the subclasses and return it using super, but I don't want to unless there is no other way.

Please help

Thanks

1 Answer 1

6

You're trying to call an instance method in a static way, and since the method isn't static, this won't work. You must

  • create a concrete instance of a Command object -- created from a non-abstract class that extends Command.
  • Call a method on that instance, not in a static way.

i.e.,

public class SeperateClass {

  //  rest of code
  public void someMethod() {
    Command myCommand = new ConcreteCommand();
    System.out.println(myCommand.getCurrentVariableName());
  }
}

Just curious, but why is Command abstract to begin with?


Edit
You state in a comment below:

Can you provide a link that will help me do this?

You need to give us more background into your problem I think, but for general review, you can learn more about abstract classes here: Abstract Methods and Classes Tutorial


Edit 2
You state in comment:

If I remove the abstract, an error says that the Command class is not abstract

You may be fixing the error in the wrong way. Often the best solution to this type of error is to fix the problem that the compiler is complaining about, not to make the class abstract. For instance, this error is often seen in classes that are declared to implement an interface, and if you neglect to give the class all of the methods declared by the interface, the compiler will give you this error message. In that situation, you shouldn't make the class abstract, but instead should give it the necessary methods.

You will want to tell us more of the details of this error.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I will try this. I'll see if I can remove the abstract
If I remove the abstract, an error says that the Command class is not abstract.
@user2891805: Please see Edit 2 to answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.