Welcome to the first lesson on inheritance
Let's try to understand what inheritance does
In Java inheritance is supported by the "extends" keyword
Now let's examine this class called Employee
Employee has got one attribute called salary and
a getter method and a setter method. deal
No big deal, a simple class
I have written another class called Manager and Manager has no method
and no attribute
I've written a class called Test with a main method
Now, in main, Test creates a new Manager object
called m and calls its setSalary method
as well as the getSalary method
Hold on! There's nothing in Manager, which means that this
should result in a compilation error. Let's try.
javac Test.java
and yes, the error is "cannot find symbol"
and the symbol is setSalary on line 4
which is this one. Expected.
Now let's do a bit of magic. Let me change the
way Manager is declared.
Manager extends Employee.
Save all. Let me try to compile Test again
and hey, this time it works
I try to run Test, it works as well.
which seems to imply that m, the instance of Manager
has got a setSalary method
as well as a getSalary method. And why is that the case?
now the reason is because of these two words ("extends Employee")
When Manager extends Employee,
Manager becomes
the child class
or the sub class
of Employee, which we call the parent class
or super class.
OK, they mean the same thing.
Manager has inherited everything from Employee.
including the salary attribute, as well as
the getSalary method and the setSalary method
It will be as if the code has been written here
and that is the reason why
when you call the setSalary method of the instance of Manager
there is no problem. So that's what inheritance is all about.
Let's push it a bit... I've written some code here which I am going to paste
into Manager.
I'm declaring an attribute called bonus
getBonus, setBonus. Let's modify Test a bit
besides calling setSalary, I am going to call
m's setBonus as well as
its getBonus method.
Save it
Try to compile Test again and run it
No problem! So how many methods are there altogether in Manager?
4. (i) setSalary, inherited from Employee.
(ii) setBonus, written in manager
(iii) getSalary, inherited from Employee and (iv) getBonus
written in Manager. So what is
inheritance all about? Inheritances is about code reuse.
Someone has written an Employee class, and you are writing a Manager class
and you realize that, hey, a Manager is
actually a specialized form of Employee and has a salary as well.
so why don't you extend Employee, inherit everything
and add on new stuff which is found
in a Manager class but not in the more generic Employee class
which is, in this case, a bonus. So a Manager
is an Employee. And he is a special Employee,
an Employee with a bonus.
so he has got the Employee's salary
as well as a special attribute called bonus
together with the getter and setter methods not found in a normal Employee.
That's inheritance.
Không có nhận xét nào:
Đăng nhận xét