Let’s check the opposite: “Are all circles ellipses?”. Otherwise, we will be contradicting the mathematical definition. The question is: “Are all ellipses circles?” The answer is no. Let’s test this result using the semantic meaning of the relationship. If we use the number of attributes on each class to decide if there is inheritance, the class Ellipse inherits from the class Circle. The class Ellipse is defined by a centre and two points called the minor radius and mayor radius. The class Circle is defined by two attributes, centre and radius. Which one is the parent class and which one the child class? It can be easily proved with the following example.Ĭonsider the classes Ellipse and Circle. Many resources explain inheritance stating that class B inherits from a class A if the attributes of class A are a subset (less in amount) of the attributes of class B. A wrong approach that you will see in several placesĪ word of caution. The answer is yes, therefore the class Student must inherit from the class Person.Īs you can see, if you follow this method is quite easy to identify inheritance. Let’s check another question “Are all students people?”. The answer is no, therefore the class Person cannot inherit from the class student. Let’s formulate the question “Are all people students?”. We have a class that represent people (class Person) and another class that represent students (class Student). If that sentence makes sense, then B must inherit from A. Also, you can formulate the sentence “all B’s are A’s”. If the answer to this question is yes, then class B must inherit from class A. However, you will be able to find that there is one approach that is always valid and is to make the following question: There are several ways that this topic is explained in different books. The big question is when class B must inherit from class A? In other words, how can we identify inheritance? How to identify inheritance in object-oriented programming? Another notation that is commonly used is A is the base class and B is a derived class. Similarly, when class B inherits from class A, we say that B is the child class and A is the parent class. In that case, we refer to ourselves like the children and the people that we inherit from as our parents. We can think about inheritance almost in the same way that we inherit things (surname, traditions, etc.) from our parents. However, it is not a principle on its own, it is one of the most important techniques that help us to follow one of the principles: code reuse. Sometimes is confused with one of the principles of object-oriented programming. It gives us the ability to reuse code and therefore, make our code clearer and easier to maintain. Inheritance in object-oriented programming is a powerful mechanism. What is inheritance in object-oriented programming?
0 Comments
Leave a Reply. |