Change return value in class without changing class itself?

Ok, let me say that I have a class called Pancake.

Pancake.java will look something like this:

public class Pancake {
    public boolean shouldEat() {
        return false;
    }
}

Now I do not want to edit Pancake.java at all. All I want to do is change what returns shouldEat()from another class, such as "NotPancake.java".

I know that I had something like

public boolean eat = false;

I could just change this by doing something like Pancake.eat = true, but is there a way to change what returns shouldEat()without editing the class in a similar way?

Thank.

+3
source share
2 answers

The way to do this is based on object-oriented programming.

public class NotPancake extends Pancake {

 @Override
 public boolean shouldEat() {
        return true;
    }
}

, , "" , OO.

, , , Pancake.

, NotPancake Pancake. NotPancake - .

 Pancake p = new Pancake();
 Pancake q = new NoPancake(); 

 print(p.shouldEat()); //Will be false
 print(q.shouldEat()); //Will be true

, , .

, , . Java @Override, .

. , , composition. .

. interface. - , , .

public interface Dish {

   boolean isEatable();

}

.

 public class Pancake implements Dish {
  @Override
  public boolean shouldEat() {
     return false;
  }
}

public class Carrot implements Dish {

 @Override
 public boolean shouldEat() {
     return true;
  }
}

.

 Dish dish1 = new Pancake();
 Dish dish2 = new NoPancake(); 

 print(dish1.shouldEat()); //Will be false
 print(dish2.shouldEat()); //Will be true

. .

+7
Pancake p = new Pancake() {
   public boolean shouldEat() {
      return true;
   }
 };
+3

All Articles