instantiating an abstract class in JAVA?

2020-07-23 06:19发布

I am learning JAVA and following the book JAVA:The Complete Reference by Herbert Shildt.

I learned about abstract classes in Java, but could not understand reason behind this line:

An abstract class cannot be directly instantiated with new operator.

I searched over web and stackoverflow and followed these questions: Why can't we instantiate a abstract class in JAVA? and Why can't we instantiate an interface or an abstract class in java without an anonymous class method?

In one answer, someone wrote as:

Simply, in a good object oriented program, you should never want to instantiate an abstract class or interface. If you do, the design is probably wrong.

I do not understand why it is important not to instantiate an abstract class for good OOP design. If someone can give a good explanation, then please help.

8条回答
戒情不戒烟
2楼-- · 2020-07-23 06:40

Abstract classes sole purpose is to be extended. The abstract class will contain common code for all its subclasses and the subclasses will only implement those sections that is relevant to it.

Abstract classes are quite useful for the Command pattern. For example, let's say you have a task that needs to execute a set of actions, then you can define a Command abstract class:

public abstract class Command
  public void doCommand() {
    // Actual code here doing stuff...
    runInternal();
    // more code;
  }

  public abstract void runInternal();
}

The idea now is that you can implement a whole range of commands, for example:

public void RedCommand extends Command {
   public void runInternal() {
     // Real code that does red things
   }
}

...and also

public void BlueCommand extends Command {
   public void runInternal() {
     // Real code that does blue things
   }
}

Now, you can have something like this:

List<Command> list = new ArrayList<>();
list.add(new RedCommand())
list.add(new RedCommand())
list.add(new BlueCommand())

for(Command c : list) {
  c.doCommand();
}

Now it's easy to add more commands later, by simply extending the Command abstract class and implementing the runInternal() method. As with all things, this pattern can/is heavily abused, but in the right environment is makes for easy/readable code.

查看更多
戒情不戒烟
3楼-- · 2020-07-23 06:47

Abstract classes are meant to provide a skeleton structure so there is no concrete implementation in them.

The child classes are expected to fill in the implementation and hence they can be instantiated.

查看更多
登录 后发表回答