Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question On OOPs

Tags:

java

oop

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.

like image 759
Pritpal Avatar asked Jul 31 '11 08:07

Pritpal


1 Answers

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".

like image 72
Jon Skeet Avatar answered Sep 17 '22 17:09

Jon Skeet