Example of Polymorphism in object oriented programming

Опубликовано: 24 Январь 2023
на канале: Nika vs Code
332
8

🔻 The real code example 🔻
In Java it would look like that:
We have an abstract class called Shape. The abstract keyword means that there might be properties or behaviors that are not defined and would need to be defined by its children.

abstract class Shape
{
// doesn't have a concrete formula
public abstract int CalculateArea();
}

class Rectangle extends Shape
{
public Rectangle(int w, int h)
{
this.width = w;
this.height = h;
}
//same method but have a concrete implementation that fits Rectangle
public int CalculateArea()
{
return width * height;
}
}

class Triangle extends Shape
{
public Triangle(int base, int h)
{
this.width = base;
this.height = h;
}

//same method but have a concrete implementation that fits Triangle
public int CalculateArea()
{
return width * height / 2;
}
}

What are the benefits?
As a client, you may know that Shape class has a method CalculateArea. This guarantees that all the classes that derive from this will have this method with the same name. This saves you as a developer a lot of time because if we wouldn't have polymorphism, and the ability to override methods, we would need to check out all the classes in order to understand what we can do with them.

❓❓❓ Do you have any other polymorphism-related questions? Ask below 👇

#nikavscode #programmingtips #codingcommunity #oopprogramming #polymorphisminjava #developerslife #learnprogrammingfromphone


Смотрите видео Example of Polymorphism in object oriented programming онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Nika vs Code 24 Январь 2023, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 332 раз и оно понравилось 8 людям.