Inheritance
This is the way derived classes can make use of the functionality in the base class.
This allows you to define a class based on an existing class giving your new class all the behavior and functionality of the existing class.
If classes do not explicitely derive from another class, then they are derived from the Object class.
Derived classes can add or modify the functionality inherited from the base classes
Multiple Inheritance
This is the ability to derive from more than one class
In VB classes can only derive from one class and therefore does not support multiple inheritance.
In VB however classes can implement multiple interfaces
The ability to implement multiple interfaces accomplishes much the same thing.
Infact some object oriented programmers might argue that multiple interfaces is superior to multiple classes because it provides the equivalent capability but with less confusion.
A derived class can only have one base class ?
Inheriting Base Class Members
When a derived class inherits from a base class it inherits everything
If you want to change the behaviour of the base class you have two options:
1) Replacing the base class member (new). Also known as hiding or shadowing.
2) Extending the base class member (virtual + override).
Base Class Members - Replacing
The "new" modifier hides (and replaces) a member from the base class with a new one
Use the new modifier to explicitley hide a member inherited from a base class which has the same name
Try and avoid using method hiding where possible as it leads to a lot of confusion.
When you don't want to override an existing method just use a different name.
class Base
{
public void Method1()
{
System.Console.WriteLine("Base - Method1");
}
}
class Derived : Base
{
// public void Method1
// new public void Method1
public new void Method1()
{
System.Console.WriteLine("Derived - Method1");
}
}
class Program
{
static void Main(string[] args)
{
Base B = New Derived()
B.Method1(); //Base - Method1
}
}
The compile-time type is Base
The run-time type is Derived
For non-virtual methods the compile-time type is used.
Base Class Members - Extending
Derived classes can define override methods that can extend the base class method.
class Base
{
public virtual void Method2()
{
System.Console.WriteLine("Base - Method2");
}
}
class Derived : Base
{
public override void Method2()
{
System.Console.WriteLine("Derived - Method2");
}
}
class Program
{
static void Main(string[] args)
{
Base B = New Derived()
B.Method2(); //Derived - Method2
}
The compile-time type is Base
The run-time type is Derived
For virtual methods the run-time type is used.
Inherits - VB.Net
Makes a class gain all the behaviour of another class, so you don't have to implement them yourself.
Important
Unlike Java methods are not virtual by default.
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext