[ Why abstract class allows to define a concrete method inside it ]
I have an abstract class A,which allows some abstract method and also concrete method.My question is that why abstract class allows concrete method to be declared ,because we are using abstract class as a superclass and use the structure in the extended classes.Can anyone help me with this?
abstract class A{
public void aMethod(){
System.out.println("Inside method");
}
}
Answer 1
An abstract class is there to let you share implementation, in addition to sharing an interface. An abstract class with only abstract methods would be pretty much like an interface, except it would let you share data members. This is not as powerful as letting you share some implementation.
Consider, for example, the Template Method pattern, which relies on the ability of abstract classes to share implementation. The template method performs the operation in a way that is common to all subclasses, letting subclasses supply the specifics.
Here is a very simple class hierarchy that illustrates this point:
abstract class AbstractCreature {
protected abstract String myName();
public void sayHi() {
System.out.println("Hello, " + myName());
}
public void sayBye() {
System.out.println("Good bye, " + myName());
}
}
class Dolphin extends AbstractCreature {
@Override
protected String myName() {
return "dolphin";
}
}
class Bunny extends AbstractCreature {
@Override
protected String myName() {
return "bunny";
}
}
class Unicorn extends AbstractCreature {
@Override
protected String myName() {
return "unicorn";
}
}
This setup lets dolphins, bunnies, and unicorns to share the functionality inherited from the abstract class (i.e. the ability to say hello and goodbye). The functionality, in turn, relies on an override of the abstract method supplied in the subclass.
if an abstract class allows concrete method, then what is the difference from a normal class?
That's a fair question. The difference is that marking a class abstract tells programmers who use it that the class must be inherited in order to be useful; a regular class, on the other hand, is expected to be useful right out of the box, without inheritance.
Answer 2
Abstract class are not pure interfaces.
You can think of an Abstract class as mix between concrete classes and interfaces. They allow you to provide common behaviour for all sub classes of the abstract class.
For example a door will always open the same way, you operate the handle and push. So you could define an abstract class for door:
Abstract class Door {
public abstract void operateHandle();
public abstract void push();
public open() {
operateHandle();
push();
}
}
This allows you to define how the handle for the door will operate in sub classes but define how the general case for a door operates.