Inheritance
“What is inheritance in C#, and in what order do the constructors run?”
One class is built on another and gets its data and methods. Write the shared part once.
See it
1/10Before. Loan and Lease each hold their own copy of Balance and .
In plain words
Inheritance lets one class (the child) be built on another (the parent, or base class). class Loan : Contract means every Loan has everything a Contract has, plus its own extras. Building a Loan makes one object; the parent's constructor runs first, then the child's. You then call the parent's methods on that same object, with no extra .
- Inheritance is an "is-a" relationship (a Loan is a Contract):
class Loan : Contractgives Loan every member of Contract that is not , so shared code lives in one place. - C# allows one base class only, but any number of .
- Constructor order: the base constructor runs first, then the derived one. A derived constructor passes values up with .
- Inherited methods are called on the same object:
loan.ApplyPayment(200)runs Contract's code against this Loan's data. refers to the current object; reaches the parent's version of a member.
In the lending API
The parent, one child, and the code that builds and uses it. Press Next line to walk through them.
Lending.sln · where these 3 files sit
- src/
- Domain/
- Billing/
- Domain/
What they ask next
Interviewers check that you can explain every line. Tap a question to open it.
What does mean, and when do you write it?
is the object the code is running on right now. Inside , and are the same. You write when a parameter has the same name as a member, or to call another constructor of the same class with .
When do you need outside the constructor line?
When a child replaces a parent method but still wants the parent's version too: calls the parent's code. That is covered on .
What if the parent has no constructor without parameters?
Then every child constructor must call with values, or it will not compile. Here Contract needs a balance, so Loan must pass one up.
Can a child use the parent's private members?
No. Private stays inside Contract. That is why Loan cannot write Balance directly; it calls . Mark a member to let children use it (see ).
Can a class inherit from two classes?
No, C# allows one base class. It can implement many interfaces. Deep chains (A : B : C : D) get hard to change, so teams keep them shallow, one or two levels.
Traps
- Don't say
Calling on a Loan creates a Contract object first.SayThere is one object. The Contract part is inside it from the moment ran. - Don't say
The child constructor runs, then the parent's.SayParent first. The child's body runs once the parent part is ready.