public class Car
{
public char color;
public char getColor()
{
return color;
}
public void setColor(char color)
{
this.color = color;
}
}
public class MyCar
{
private Car car = null;
public MyCar()
{
this.car = new Car();
car.color = 'R';
}
}
Which OOPS principle does the above code violate?
• Abstraction
• Encapsulation
• Polymorphism
• None of the above
I understand that Encapsulation is the answer to this problem. Just wanted to know if other option is also true.
Well, I would view it in these terms:
Encapsulation: by allowing direct access to the color
field, the Car
class is exposing an implementation detail. Ignacio has shown that he doesn't view this type of violation as one of encapsulation, but of data hiding - my own view of the word "encapsulation" is that it includes data hiding. That just goes to show how these words can be used in different ways.
Polymorphism: judging by the names MyCar
and Car
should potentially implement a common interface or have a common base class. At least, the classes given can't be used polymorphically.
Abstraction: I would argue that using char
as the abstraction for a color is inappropriate. Whether that's an abstraction violation or not again depends on what you mean by "abstraction violation".
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