Inheritance relationship example

C++ Inheritance

inheritance relationship example

An inheritance relation, named Is-a: class C2 is a An Example of Aggregation Then the class picture aggregates point, using the generalized relation Has-a. For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For example, House is a Building. But Building is not a House. “IS-A” relationship is a totally based on Inheritance, which can be of two types Class For example is “Apple is a fruit”, “Ferrari is a car”.

This Object class defines and implements the common behaviors that are required of all the Java objects running under the JRE.

These common behaviors enable the implementation of features such as multi-threading and garbage collector. Superclass Person and its Subclasses Suppose that we are required to model students and teachers in our application. We can define a superclass called Person to store common properties such as name and address, and subclasses Student and Teacher for their specific properties.

For students, we need to maintain the courses taken and their respective grades; add a course with grade, print all courses taken and the average grade. Assume that a student takes no more than 30 courses for the entire program. For teachers, we need to maintain the courses taught currently, and able to add or remove a course taught. Assume that a teacher teaches not more than 5 courses concurrently.

We design the classes as follows. Paul Tan 8 sunset way IM added. IM cannot be added. IM cannot be removed. Inheritance "A line is composed of 2 points" vs. We have seen that a Line class can be implemented using composition of Point class - "A line is composed of two points", in the previous section.

A Line can also be implemented, using inheritance from the Point class - "A line is a point extended by another point".

inheritance relationship example

Let's call this subclass LineSub to differentiate from the Line class using composition. This is the same test driver used in the earlier example on composition, except change in classname. Study both versions of the Line class Line and LineSub. I suppose that it is easier to say that "A line is composed of two points" than that "A line is a point extended by another point".

Use composition if possible, before considering inheritance. Use inheritance only if there is a clear hierarchical relationship between classes.

It comes from Greek word "poly" means many and "morphos" means form. For examples, in chemistry, carbon exhibits polymorphism because it can be found in more than one form: But, each of the form has it own distinct properties and price. Substitutability A subclass possesses all the attributes and operations of its superclass because a subclass inherited all attributes and operations from its superclass.

This means that a subclass object can do whatever its superclass can do. As a result, we can substitute a subclass instance when a superclass instance is expected, and everything shall work fine.

This is called substitutability. In our earlier example of Circle and Cylinder: Cylinder is a subclass of Circle. We can say that Cylinder "is-a" Circle actually, it "is-more-than-a" Circle. Subclass-superclass exhibits a so called "is-a" relationship. The reference c1, however, retains its internal identity.

inheritance relationship example

In our example, the subclass Cylinder overrides methods getArea and toString. This is because c1 is in fact holding a Cylinder object internally. Summary A subclass instance can be assigned substituted to a superclass' reference. Once substituted, we can invoke methods defined in the superclass; we cannot invoke methods defined in the subclass. However, if the subclass overrides inherited methods from the superclass, the subclass overridden versions will be invoked.

Consider the following example. Suppose that our program uses many kinds of shapes, such as triangle, rectangle and so on.

OOP Inheritance & Polymorphism - Java Programming Tutorial

We should design a superclass called Shape, which defines the public interfaces or behaviors of all the shapes. For example, we would like all the shapes to have a method called getAreawhich returns the area of that particular shape. The Shape class can be written as follow.

We shall print an error message for the time being. In the later section, I shall show you how to resolve this problem.

inheritance relationship example

We can then derive subclasses, such as Triangle and Rectangle, from the superclass Shape. A Test Driver TestShape. You could instantiate different subclass instance, and the code still works. You could extend your program easily by adding in more subclasses, such as Circle, Square, etc, with ease. Nonetheless, the above definition of Shape class poses a problem, if someone instantiate a Shape object and invoke the getArea from the Shape object, the program breaks. We do not want anyone to instantiate a Shape instance.

This problem can be resolved by using the so-called abstract class. For example, in our game app, we have many types of monsters that can attack. We shall design a superclass called Monster and define the method attack in the superclass. The subclasses shall then provides their actual implementation. In the main program, we declare instances of superclass, substituted with actual subclass; and invoke method defined in the superclass.

This is because, in a UML class diagram, subclass is often drawn below its superclass. Upcasting is always safe because a subclass instance possesses all the properties of its superclass and can do whatever its superclass can do. The compiler checks for valid upcasting and issues error "incompatible types" otherwise. This is called "downcasting". Downcasting is not always safe, and throws a runtime ClassCastException if the instance to be downcasted does not belong to the correct subclass.

A subclass object can be substituted for its superclass, but the reverse is not true.

inheritance relationship example

Point cannot be casted to Circle The "instanceof" Operator Java provides a binary operator called instanceof which returns true if an object is an instance of a particular class. The syntax is as follows: When a superclass instance is expected, it can be substituted by a subclass instance. In other words, a reference to a class may hold an instance of that class or an instance of one of its subclasses - it is called substitutability.

If a subclass instance is assign to a superclass reference, you can invoke the methods defined in the superclass only. You cannot invoke methods defined in the subclass. However, the substituted instance retains its own identity in terms of overridden methods and hiding variables. If the subclass overrides methods in the superclass, the subclass's version will be executed, instead of the superclass's version.

This can be resolved via abstract method and abstract class. An abstract method is a method with only signature i. You use the keyword abstract to declare an abstract method. For example, in the Shape class, we can declare abstract methods getAreadrawetc, as follows: How to compute the area if the shape is not known? Implementation of these abstract methods will be provided later once the actual shape is known.

These abstract methods cannot be invoked because they have no implementation. A class containing one or more abstract methods is called an abstract class. An abstract class must be declared with a class-modifier abstract. Shape and its Subclasses Let us rewrite our Shape class as an abstract class, containing an abstract method getArea as follows: The abstract Superclass Shape.

C++ Inheritance

Therefore, an abstract class cannot be instantiated. In other words, you cannot create instances from an abstract class otherwise, you will have an incomplete instance with missing method's body. To use an abstract class, you have to derive a subclass from the abstract class. In the derived subclass, you have to override the abstract methods and provide implementation to all the abstract methods.

The subclass derived is now complete, and can be instantiated. If a subclass does not provide implementation to all the abstract methods of the superclass, the subclass remains abstract. This property of the abstract class solves our earlier problem. In other words, you can create instances of the subclasses such as Triangle and Rectangle, and upcast them to Shape so as to program and operate at the interface levelbut you cannot create instance of Shape, which avoid the pitfall that we have faced.

The purpose of an abstract class is to provide a common interface or protocol, or contract, or understanding, or naming convention to all its subclasses. For example, in the abstract class Shape, you can define abstract methods such as getArea and draw.

No implementation is possible because the actual shape is not known. However, by specifying the signature of the abstract methods, all the subclasses are forced to use these methods' signature.

The subclasses could provide the proper implementations. Coupled with polymorphism, you can upcast subclass instances to Shape, and program at the Shape level, i,e. The separation of interface and implementation enables better software design, and ease in expansion. For example, Shape defines a method called getAreawhich all the subclasses must provide the correct implementation.

You can ask for a getArea from any subclasses of Shape, the correct area will be computed. Furthermore, you application can be extended easily to accommodate new shapes such as Circle or Square by deriving more subclasses.

Program at the interface, not at the implementation. That is, make references at the superclass; substitute with subclass instances; and invoke methods defined in the superclass only. An abstract method cannot be declared final, as final method cannot be overridden. An abstract method, on the other hand, must be overridden in a descendant before it can be used.

An abstract method cannot be private which generates a compilation error. This is because private method are not visible to the subclass and thus cannot be overridden. Monster We shall define the superclass Monster as an abstract class, containing an abstract method attack.

The abstract class cannot be instantiated i. An interface contains only public abstract methods methods with signature and no implementation and possibly constants public static final variables. You have to use the keyword "interface" to define an interface instead of keyword "class" for normal classes.

  • Java Programming Tutorial
  • Microsoft SQL Server Producer Output

The keyword public and abstract are not needed for its abstract methods as they are mandatory. JDK 8 introduces default and static methods in the interface.

Inheritance (object-oriented programming)

It is entirely possible to derive a class whose object will behave incorrectly when used in a context where the parent class is expected; see the Liskov substitution principle. In some OOP languages, the notions of code reuse and subtyping coincide because the only way to declare a subtype is to define a new class that inherits the implementation of another.

inheritance relationship example

Using inheritance extensively in designing a program imposes certain constraints. For example, consider a class Person that contains a person's name, date of birth, address and phone number. We can define a subclass of Person called Student that contains the person's grade point average and classes taken, and another subclass of Person called Employee that contains the person's job-title, employer, and salary.

In defining this inheritance hierarchy we have already defined certain restrictions, not all of which are desirable: Singleness Using single inheritance, a subclass can inherit from only one superclass. Continuing the example given above, Person can be either a Student or an Employee, but not both. Using multiple inheritance partially solves this problem, as one can then define a StudentEmployee class that inherits from both Student and Employee.

However, in most implementations, it can still inherit from each superclass only once, and thus, does not support cases in which a student has two jobs or attends two institutions. The inheritance model available in Eiffel makes this possible through support for repeated inheritance. Static The inheritance hierarchy of an object is fixed at instantiation when the object's type is selected and does not change with time.

For example, the inheritance graph does not allow a Student object to become a Employee object while retaining the state of its Person superclass. This kind of behavior, however, can be achieved with the decorator pattern. Some have criticized inheritance, contending that it locks developers into their original design standards. Even if the superclass has not been declared public, the client can still cast the object to its superclass type. For example, there is no way to give a function a pointer to a Student's grade point average and transcript without also giving that function access to all of the personal data stored in the student's Person superclass.

The composite reuse principle is an alternative to inheritance. This technique supports polymorphism and code reuse by separating behaviors from the primary class hierarchy and including specific behavior classes as required in any business domain class. This approach avoids the static nature of a class hierarchy by allowing behavior modifications at run time and allows one class to implement behaviors buffet-style, instead of being restricted to the behaviors of its ancestor classes.

Issues and Alternatives[ edit ] Implementation inheritance is controversial among programmers and theoreticians of object-oriented programming since at least the s. Among them are the authors of Design Patternswho advocate interface inheritance instead, and favor composition over inheritance.

For example, the decorator pattern as mentioned above has been proposed to overcome the static nature of inheritance between classes. As a more fundamental solution to the same problem, role-oriented programming introduces a distinct relationship, played-by, combining properties of inheritance and composition into a new concept.