can you give me a simple example of inheritance and polymorphism, so it could be fully clear and understandable?
using C# would make it more clear, as I already learned it.
P.S: the tutors, books we've got are in native language, (arabic)
sorry if that question seemed so easy, even silly on you guys, but these concepts are considered hard; if you don't fully understand them, then you fail.
This is polymorphism:
public interface Animal
{
string Name { get; }
}
public class Dog : Animal
{
public string Name { get { return "Dog"; } }
}
public class Cat : Animal
{
public string Name { get { return "Cat"; } }
}
public class Test
{
static void Main()
{
// Polymorphism
Animal animal = new Dog();
Animal animalTwo = new Cat();
Console.WriteLine(animal.Name);
Console.WriteLine(animalTwo.Name);
}
}
this is Inheritance:
public class BaseClass
{
public string HelloMessage = "Hello, World!";
}
public class SubClass : BaseClass
{
public string ArbitraryMessage = "Uh, Hi!";
}
public class Test
{
static void Main()
{
SubClass subClass = new SubClass();
// Inheritence
Console.WriteLine(subClass.HelloMessage);
}
}
Inheritance means that if you create a class Car with a public field TankSize then you derive from it a class SuperCar the last one has inherited the field TankSize from Car.
Polymorphism is the fact that every time in the code you have a method where a Car is expected you can pass a SuperCar and it will behave like a Car.
With virtual methods defined as needed you will be calling a method on a base class but the actual object on which you are working on will execute its version of the virtual method so you will be calling SuperCar.GetPrice and not Car.GetPrice in fact.
This in few words, for more, I see the others are already answering as I write.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With