METHOD HIDING /SHADOWING
Method
hiding is also known as method shadowing type of polymorphism which deals with
the concept.
“Method hiding is a process of re-implementation the parent class
method in child class by changing its behavior while keep the same name and
signature”.
Whereas the parent class need not
to declare as virtual but still the child class has to declared with ‘new’
keyword like this. Not use of override.
Suppose if I have parent class and
its method
public class Parentclass
polymorphism method hiding |
{
public void Test()
{
Statements;
}
}
public class Childclass: Parentclas
{
public new void Test()
{
New Statements;
}
}
Here we use new keyword to
shadowing but it can be possible without using new keyword, but the compiler
raise a warning to you. We use to this keyword to make sure that the parent
method also active otherwise without using the new keyword child class method
hide the parent’s method and make it not active, if we doesn’t use new then in
future it may be chance to forget that the parent also have a same name and
signature method, and it can leads to our program fail.
Difference between method overriding and method hiding
We have two
approaches to re-implementing a parent class method under child class method which
are.
1. Method overriding ‘
2. Method hiding/shadowing
Here the detail of these differences.
METHOD
OVERRIDING
|
METHOD
HIDING/SHADOWING
|
After re-implementing the parent classes under child class how I call the parent class |
Yes! After re-implementing
a parent class under child class we are still able to call the parent class by using
two approaches.
1. By creating the parent instance in the target class we can call
the parent method like.
Parent p=new Parent ( );
2. By using the base class keyword we can also calls the parent
method form child class. But from static block we can’t use the base keyword to
call. Like this.
base. Method(); // from non-static block
so what we do to overcome this problem,
hence we need to create a new method in child class to has to make interface
for the parent class like int the child class we can create a method and use
like this.
Public void ParentMethod()
{
base. Method(); //parent method name will place
}
By using this process now we are able to call the parent
class method after re-implementing by using child class instance from a static
block and non-static block.
0 comments:
Post a Comment
Please do not enter any spam link in the comment box