2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Why avoid Java Inheritance “Extends”?

Extends leads to tightly coupling of  programming,which is problematic in some cases,when we need to make code changes to particular class where that class  has relationship with other class.Is it better to use implements instead of extends .why not implements why extends?

please suggest.


thanks in advance.


userimage

Loosely Coupling is advantage than tightly coupling,where this is possible with implements(Interface).This leads to less dependency .we make enhancements in the code with less hierarchy in future.

Example for loosely coupling using implements:

class Traveler
{
Vehicle v;
public void setV(Vehicle v)
{
this.v = v;
}

void startJourney()
{
v.move();
}
}


Interface Vehicle
{
void move();
}


class Car implements Vehicle
{
public void move()
{
// logic
}
}


class Bike implements Vehicle
{
public void move()
{
// logic
}
}
In future ,if we change  Car object or Bike object into the Traveler by calling setter method, So if Car object is replaced with Bike then no changes are required in Traveler class, this means there is loose coupling between Traveler and Vehicle object.







Answer is