Thursday, 18 June 2015

OOPS concepts and Techniques in Java

Basic Concepts
1.     Polymorphism - Many forms
Can be achieved by following two ways.
Overloading and overriding

OVERLOADING is the process of declaring the methods having the same name but diff signatures. Signature means different types & number of arguments. ONLY name should be same anything else can be different.

OVERRIDING is the process of overwriting the methods of base class in Derived Class.

Overriding is the example of run-time polymorphism and Overloading is the example of compile-time polymorphism.

Rules for writing Overloaded Methods

    1) Method can have different access specifier.
    2) Method can have different return type.
    3) Method must have same name with different method
       signatures.
    4) It doesn't need inheritance as method should be in
       Same class.

Rules for writing Override Methods

    1) Method must have same access specifier.
    2) Method must have same return type.
    3) Method must have same name with same method
       signatures.
    4) It needs inheritance and virtual keyword before it
       declaration.
    5) It requires non-static method.

2.     Inheritance - Subclass
3.     Encapsulation – Binding the data within the class
In java encapsulation is achieved by making use of access modifiers. (Keeping variables as private and providing public getters and setters)
Advanced Concepts
4.     Coupling
By definition coupling is the degree to which one class has knowledge of another or in other words one class has a dependency upon another.
/*  Tight coupling example*/
class A {
    int i;
    B b = new B();
    i = b.value;      // No encapsulation of this variable in class B!
}
class B {
    public int value; // Should be private and be accessed through public getters and setters
}
5.     Cohesion
Cohesion is all about how a single class is designed.
The term cohesion is used to indicate the degree to which a class has a single, well-focused purpose.
Keep in mind that cohesion is a subjective concept.
The more focused a class is, the higher its cohesiveness - a good thing.
/*  Low cohesion example*/
class AllInStaff {
    void getStaffSalary();
    void getStaffDetails();
    void getStaffSalesReport();
}
/*  High cohesion example*/
class Accounts {
    void getStaffSalary();
    ...
}
class Personnel {
    void getStaffDetails();
    ...
}
class SalesReporting {
    void getStaffSalesReport();
    ...
}


OOPS Techniques
1.     Abstraction- Hiding the data
To build the Car class, one does not need to know how the different components work internally, but only how to interface with them
List –is the example of abstraction- Ignore how a List is implemented and focus on what it promises to do for you
2.     Coding through Interfaces
3.     Coding through abstract classes





No comments:

Post a Comment