Today I had an interview for software engineering position. I have read many things from stackoverflow for the interview. They asked me about the normal things realated to OOP. But they also asked me about these:
Is Encapsulation possible without inheritance?
Is Abstraction possible without inheritance?
Is Polymorphism possible without inheritance?
I have answered these according to my knowledge of OOP. I don't know whether it is right or wrong. Can anyone tell me the correct answer of these with some related examples.
Thanks
Yes, because Encapsulation is the ability to hide a class properties from the outside world by means of access methods.
Well, abstraction can refer to many things, but talking about OOP: No, an abstract class cannot be used directly, you can only instantiate inherited classes.
Yes, polymorphism is the construction of a single interface to several types of objects, for instance, a single function call that can receive different classes or data types as arguments. They can be inherited or not.
Encapsulation is definitely possible without inheritance. Encapsulation is the concept of hiding data that from outside objects that should not be able to manipulate it. An example of encapsulation would be private fields of an object in Java. You can then use public methods (such as getters and setters, or other calculating methods) to manipulate the data only as needed.
Abstraction and Polymorphism, however, are directly related to inheritance.
Abstraction is when you take away the implementation details of an object and create an abstract class or an interface (speaking in terms of Java). This will act as a contract for what any implementing or inheriting class will need to include in the detailed implementation. The abstract class will have method signatures, but no body; the inheriting class will implement the bodies.
Polymorphism is the ability to implement something abstract in different forms. For example, if you have an abstract class called Animal that contained a speak() method, you could create a Dog class that inherits from Animal and implement speak() to print "woof", while a Cat() class would implement speak() to print "meow".
Note that it does depend on which type of polymorphism is being examined. You can, as stated in another answer, have method/function parameter polymorphism, and as stated that is possible without inheritance.
The answer to all three questions is Yes, it's possible to do them without inheritance, but the real answer is "It depends on the language they're implemented in".
I mean, consider that the very first C++ compiler actually compiled it's code to standard C, which is not an OOP language. Obviously, the code had to be compiled to a language that did not support inheritance.
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