Java inheritance, composition, encapsulation and polymophism
Composition means HAS A
Inheritance means IS A
Example
: Car has a Engine and Car is a Automobile
In programming this is represented as:
1 class Engine {} // The engine class. 2 3 class Automobile{} // Automobile class which is parent to Car class. 4 5 // Car is an Automobile, so Car class extends Automobile class. 6 class Car extends Automobile{ 7 8 // Car has a Engine so, Car class has an instance of Engine class as its member. 9 private Engine engine; 10 }
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as as single unit. In encapsulation the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class, therefore it is also known as data hiding.
To achieve encapsulation in Java
-
Declare the variables of a class as private.
-
Provide public setter and getter methods to modify and view the variables values.
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
runtime polymorphism and compile time polymorphism
method overriding is good example of runtime polymorphism. Parent class has a version of method A() and subclasses override this method. At compile time it does figure out which method to call. only at Run time, JVM decides which method to call based on it infers whether it is
an object of parent class or subclass.
compile time polymorphism is just method overloading in Java. A method can take different variance of arguments.