Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Liskov Substitution Principle */
- // Before
- class Rectangle {
- protected int width;
- protected int height;
- public Rectangle(int width, int height) {
- this.width = width;
- this.height = height;
- }
- public int getWidth() {
- return width;
- }
- public void setWidth(int width) {
- this.width = width;
- }
- public int getHeight() {
- return height;
- }
- public void setHeight(int height) {
- this.height = height;
- }
- public int area() {
- return width * height;
- }
- }
- class Square extends Rectangle {
- public Square(int side) {
- super(side, side);
- }
- }
- class App {
- public static void main(String[] args) {
- Rectangle rectangle = new Rectangle(20, 40);
- Square square = new Square(20);
- rectangle.area(); // 800
- square.area(); // 400
- modifyRectangle(rectangle);
- modifyRectangle(square);
- rectangle.area(); // 1000
- square.area(); // 1000 instead of 2500
- }
- static void modifyRectangle(Rectangle rectangle) {
- rectangle.setHeight(50);
- }
- }
- // After
- class Rectangle {
- private int width;
- private int height;
- public Rectangle(int width, int height) {
- this.width = width;
- this.height = height;
- }
- public int getWidth() {
- return width;
- }
- public void setWidth(int width) {
- this.width = width;
- }
- public int getHeight() {
- return height;
- }
- public void setHeight(int height) {
- this.height = height;
- }
- public int area() {
- return width * height;
- }
- }
- class Square {
- private int side;
- public Square(int side) {
- this.side = side;
- }
- public int getSide() {
- return side;
- }
- public void setSide(int side) {
- this.side = side;
- }
- public int area() {
- return side * side;
- }
- }
- class App {
- public static void main(String[] args) {
- Rectangle rectangle = new Rectangle(20, 40);
- Square square = new Square(20);
- rectangle.area(); // 800
- square.area(); // 400
- modifyRectangle(rectangle);
- modifySquare(square);
- rectangle.area(); // 1000
- square.area(); // 2500
- }
- static void modifyRectangle(Rectangle rectangle) {
- rectangle.setHeight(50);
- }
- static void modifySquare(Square square) {
- square.setSide(50);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment