Abstract class and method
“What is an abstract class? Why can't you create one, and why does it still have a constructor?”
A parent class that is only a starting point. You cannot build it on its own, and it can force every child to write certain methods.
See it
1/8Before. Contract is a normal class, so new Contract(500) builds fine.
In plain words
Mark a class when it only makes sense as a parent. The compiler then refuses on it, so a "contract that is no kind of contract" can never exist. An method has no body; every child must it or fail to build. The abstract class can still hold shared data and a constructor, because every child object has a parent part that needs setting up.
- An abstract class cannot be instantiated (built with ); it exists to be inherited. It can hold data (fields), constructors and normal methods, plus abstract members with no body.
- Every non-abstract derived class must override every abstract member, or it does not compile.
- It still has a constructor because the base part of each derived object must be set up; the derived constructor calls it with . I make it , since only derived classes can call it.
- Versus an : an abstract class shares state and code, and a class can inherit only one; an interface is a contract with no state, and a class can implement many.
In the lending API
The abstract parent, a child that compiles, and the lines that do not. Press Next line to walk through them.
Lending.sln · where these 3 files sit
- src/
- Domain/
- Billing/
- Domain/
abstract class Contract, and becomes : a method with no body.new Contract(...) will not compile.What they ask next
Interviewers check that you can explain every line. Tap a question to open it.
Abstract method vs virtual method?
: no body, every child must override it. : has a default body, a child may override it (see ). Use abstract when there is no sensible default.
Can an abstract class have no abstract methods?
Yes. It is then just a parent that cannot be built on its own. Rare, but legal.
Why not make the constructor ?
It would compile, but it is misleading: nobody outside can call it anyway, because
new Contractfails. says the truth: children only.Can a variable have an abstract type?
Yes:
Contract c = new Loan(...), or a list of Contract. The variable's type can be abstract; the object is always a real child.When abstract class, when interface?
Abstract class when the children share data and code (Balance, ). when unrelated classes only share a promise of methods. Many teams use both: an interface for the outside, an abstract base for shared code.
Traps
- Don't say
An abstract class has no constructor, since you can't create it.SayIt has one; it runs as the first part of building every child object. - Don't say
An abstract class can only have abstract methods.SayIt can have fields, constructors and normal methods too. That is the difference from an interface.