This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
force base class to use its own method and not overrided method
Suppose I have these classes — sorry, it's kind of hard to think of a simple example here; I don't want any why-would-you-want-to-do-that answers! –:
class Squarer
{
public void setValue(int v)
{
mV = v;
}
public int getValue()
{
return mV;
}
private int mV;
public void square()
{
setValue(getValue() * getValue());
}
}
class OnlyOddInputsSquarer extends Squarer
{
#Override
public void setValue(int v)
{
if (v % 2 == 0)
{
print("Sorry, this class only lets you square odd numbers!")
return;
}
super.setValue(v);
}
}
// auto s = new OnlyOddInputsSquarer();
OnlyOddInputsSquarer s = new OnlyOddInputsSquarer();
s.setValue(3);
s.square();
This won't work. When Squarer.square() calls setValue(), it will go to OnlyOddInputsSquarer.setValue() which will reject all its values (since all squares are even). Is there any way I can override setValue() so that all the functions in Squarer still use the method defined there?
PS: Sorry, Java doesn't have an auto keyword you haven't heard about! Wishful thinking on my part.
Edit: I can't modify Squarer!
It seems to me that the class Squarer is not well designed. If you really need a dirty trick to make this work, you could also override the method square():
class OnlyOddInputsSquarer extends Squarer
{
#Override
public void setValue(int v)
{
if (v % 2 == 0)
{
print("Sorry, this class only lets you square odd numbers!")
return;
}
super.setValue(v);
}
#Override
public void square()
{
super.setValue(getValue() * getValue());
}
}
But... a square of a odd number is not even, so this should not really be a problem. I suppose this is just an example and your real problem is different.
Edit: OK, if this doesn't work, there is even a dirtier method: in setValue check the stack and if it was called from square call super.setValue instead. I don't recommend this, but If you really really need to get this done, check here to see how to do it.
This would be relatively painless solution I think. It postpones the check until the actual squaring is done.
public class OnlyOddInputsSquarer extends Squarer {
#Override
public void square() {
if (getValue() % 2 == 0) {
throw new IllegalStateException("Sorry, this class only lets you square odd numbers!")
}
super.square();
}
}
And here is its unit test (requires JUnit):
public class OnlyOddInputsSquarerTest {
#Test
// normally this case would be in a separate test
public void testSuperclass() {
Squarer squarer = new Squarer();
squarer.setValue(3);
squarer.square();
Assert.asserEquals(9, squarer.getValue());
}
#Test
public void testOddValue() {
OnlyOddInputsSquarer oddSquarer = new OnlyOddInputsSquarer();
oddSquarer.setValue(3);
try {
oddSquarer.square();
Assert.fail("Expected IllegalStateException");
catch(IllegalStateException e) {
// expected
}
}
#Test
public void testEvenValue() {
OnlyOddInputsSquarer oddSquarer = new OnlyOddInputsSquarer();
oddSquarer.setValue(4);
oddSquarer.square();
Assert.asserEquals(16, squarer.getValue());
}
}
Related
I ran into a bit of an issue and was hoping someone could tell me what I'm missing here.
for some context I have the following methods:
private boolean windowork;
public class WinidowMalfunction extends Event {
ControllerException newException = new ControllerException("Error:");
public WinidowMalfunction(long delayTime) {
super(delayTime);
}
public void action() throws ControllerException {
windowork = false;
someThingWentWrongHere(1, "Error at WinidowMalfunction");
}
}
private boolean poweron;
public class PowerOut extends Event {
public PowerOut(long delayTime) {
super(delayTime);
}
public void action() throws ControllerException {
poweron = false;
someThingWentWrongHere(2, "Error at powerOut event");
}
}
and I'm creating interface Fixable where I need to change the value of poweron and windowork to change their values to true. but I can't get the FIxable to accept the references. they are all in the same class so is there a way to reference these boolean function in an interface
EDIT:
Assignment question:
In this part, we add functionality for restoring the saved GreenhouseControls object and having it resume execution where it left off. It demonstrates the use of interfaces and the capability of Java methods to return objects.
Create the following interface
interface Fixable {
// turns Power on, fix window and zeros out error codes
void fix ();
// logs to a text file in the current directory called fix.log
// prints to the console, and identify time and nature of
// the fix
void log();
}
You can do something like this:
interface Fixable {
public boolean setTrue();
}
class Foo implements Fixable {
private boolean windowork = false;
public void setTrue() {
windowork = true;
}
}
class Bar implements Fixable {
private boolean poweron = false;
public void setTrue() {
poweron = true;
}
}
The only advantage of the above is if you had an array of Fixable objects you could iterate thru them and do this.
for (Fixable f : fixableArray) {
f.setTrue();
}
An interface can be designed in a way to read-write a boolean property that resides in the class/instance.
public interface Somename {
public boolean isPowerOn();
public void setPowerTo(boolean arg);
}
I have 2 enums and 2 interfaces that I am trying to create in a specific way. The goal is to form a hierarchy where I can declare a list of methods that belong to one enum and a differnent list of values that belong to the combination of both enums.
For example: the methods declared within LevelOneOperations should belong to LevelOne only. Then methods declared witin LevelTwoOperations should belong to the combination of both together like A.1, A.2, A.3, etc.
public enum LevelOne implements LevelOneOperations {
A {
public boolean isValid(Request obj){ // logic }
public void prepare(Request obj){ // logic }
},
B {
public boolean isValid(Request obj){ // logic }
public void prepare(Request obj){ // logic }
} ...
}
public enum LevelTwo implements LevelTwoOperations {
1 {
public void process(LevelOne lev1, Request obj){
switch(lev1){
case A: // do something
case B: // do something else
case C: // do something else
case D: // do the last thing
}
}
},
2 {
public void process(LevelOne lev1, Request obj){ // logic }
} ...
}
public interface LevelOneOperations {
public boolean isValid(Request obj);
public void prepare(Request obj);
}
public interface LevelTwoOperations {
public void process(LevelOne lev1, Request obj);
}
public class myService {
public void runProcess(Request obj){
LevelOne l1 = LevelOne.valueOf(obj.getLevel1());
LevelTwo l2 = LevelTwo.valueOf(obj.getLevel2());
if(l1.isValid()){
l1.prepare();
l2.process(l1, obj);
}
}
}
Is there a way I can create an enum hierarchy so that I don't need to use switch statements to control the flow of the application. I want to call the process like: LevelOne.LevelTwo.process(obj);
I need methods that apply to LevelOne for all types and some methods that apply to LevelOne.LevelTwo together so that I have a grouped enum like : A.1, A.2, A.3, B.1, B.2, B.3, C.1, C.2, C.3, D.1, D.2, D.3, etc. I am also trying to make it easy to expand upon in the future because these lists are only subsets of what we are expecting for this project.
Tomorrow if I want to add a new LevelOne like E or a new LevelTwo 4 then it shouldn't require a lot of rework to introduce and support a new constant like that. The internal business logic between each element is different. Even between sub levels like: A.1 and A.2 will be different because both enumerators are taken into consideration and effect the output of the process.
The only way that I can think of to implement any thing like this is through switch/case statements. Can you please let me know if there is another way that I can achieve this?
I don't want separate classes for each variation because it will be a lot of different service classes and this is for only one part of my application. Currently I would have 5 elements in my first enumerator and 2 elements in my second enumerator for a total of 10 combinations.
You can use the Visitor pattern for this.
If you add a new enum to either of them, you're forced to implement all the new methods before the code will compile, unlike with a switch where you won't get compilation error if you miss one.
interface VerbAction {
void run();
void walk();
void jump();
}
enum Verb {
Run { #Override void perform(VerbAction action) { action.run(); } },
Walk { #Override void perform(VerbAction action) { action.walk(); } },
Jump { #Override void perform(VerbAction action) { action.jump(); } };
abstract void perform(VerbAction action);
}
enum Noun {
Dog {
#Override
void perform(Verb verb) {
verb.perform(new VerbAction() {
#Override
public void run() {
// Running dog
}
#Override
public void walk() {
// Walking dog
}
#Override
public void jump() {
// Jumping dog
}
});
}
},
Cat {
#Override
void perform(Verb verb) {
verb.perform(new VerbAction() {
#Override
public void run() {
// Running cat
}
#Override
public void walk() {
// Walking cat
}
#Override
public void jump() {
// Jumping cat
}
});
}
},
Pony {
#Override
void perform(Verb verb) {
verb.perform(new VerbAction() {
#Override
public void run() {
// Running pony
}
#Override
public void walk() {
// Walking pony
}
#Override
public void jump() {
// Jumping pony
}
});
}
};
abstract void perform(Verb verb);
}
Problem Description:
I want to be able to pass around a list of methods to other classes where the methods have been defined in only one class. If the methods, some of which have input parameters and non-void return types, are defined in one class, I want to be able to pass a list of some of them, with possible duplicates, as a parameter to some other class's constructor.
Code Description:
The code below is a crude example and can be ignored if it detracts from the main goal. Another example, in addition to the one below, would be a case where the methods are int Add(int n1, int n2), int Subtract(int n1, int n2), Multiply, etc.. and the interface has a method called int MathOperation(int n1, int n2).
Attempt to solve the problem:
The adapter pattern seems to have the functionality I'm looking for but I have only seen examples where the methods in the interface have no input or output parameters. An example implementation I wrote just for this question is posted below.
Problem Analogy:
You have a random picture generator web service. There are 30 mutations that can be applied to an image. The client connects and clicks a "generate" button and a random list of some of those functions are passed to some other class within the web service which then proceeds to run those functions with it's own data while also collecting and possibly re-using the return values to generate some mutated cat image. It can't just explicitly call the methods in the other class because that process needs to be done randomly at run-time. That is why I lean towards the idea of generating a random list of methods which are executed in-order when the 'generate' button is clicked.
I hope I have been clear.
public class SomeClass {
...
public double UseWrench(double torque, boolean clockwise) { ... }
public double UsePliers(double torque, boolean clockwise) { ... }
public double UseScrewDriver(double torque, boolean clockwise) { ... }
public boolean UseWireCutters(double torque) { ... }
interface IToolActions {
double TurnFastener(double torque, boolean clockwise);
boolean CutWire(double torque);
}
private IToolActions[] toolActions = new IToolActions[] {
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UseWrench(double torque, boolean clockwise); } },
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UsePliers(double torque, boolean clockwise); } },
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UseScrewDriver(double torque, boolean clockwise); } },
new IToolActions() { public boolean CutWire(double torque) { boolean UseWireCutters(double torque); } },
};
}
public class Worker<T> {
public List<? extends IToolActions> toolActions;
public Worker(List<? extends IToolActions> initialToolSet){
toolActions = initialToolActions;
}
}
While #alainlompo has the general idea, Java 8 simplifies this greatly by using something such as BiConsumer (for doubles) or even just a Consumer for the class object. In fact, you can go really crazy, and have a method accept varargs lambdas:
public class SomeClass
public double useWrench(double torque, boolean clockwise) { ... }
public double usePliers(double torque, boolean clockwise) { ... }
public double useScrewDriver(double torque, boolean clockwise) { ... }
public boolean useWireCutters(double torque) { ... }
}
public class Worker {
#SafeVarargs
public Worker(SomeClass example, Consumer<? extends SomeClass>... operations) {
for (Consumer bc : operations) {
bc.accept(example);
}
}
}
Then, this is easily simplified:
SomeClass c = new SomeClass();
new Worker(c, SomeClass::useWrench, SomeClass:usePliers, SomeClass::useScrewDriver, SomeClass::useWireCutters);
While it seems a little awkward applying it like that (due to it being an Adapter pattern), you can easily see how this could apply to a class body:
public class SomeClass
public double useWrench(double torque, boolean clockwise) { ... }
public double usePliers(double torque, boolean clockwise) { ... }
public double useScrewDriver(double torque, boolean clockwise) { ... }
public boolean useWireCutters(double torque) { ... }
#SafeVarargs
public void operate(Consumer<? extends SomeClass>... operations) {
for (Consumer<? extends SomeClass> bc : operations) {
bc.accept(example);
}
}
}
//Elsewheres
SomeClass c = new SomeClass();
c.operate(SomeClass::useWrench, SomeClass:usePliers, SomeClass::useScrewDriver, SomeClass::useWireCutters);
Of course, you don't need varargs, it will work just as well simply passing a Collection
But wait there's more!!!
If you wanted a result, you can even use a self-returning method via a Function, e.g.:
public class SomeClass {
public double chanceOfSuccess(Function<? super SomeClass, ? extends Double> modifier) {
double back = /* some pre-determined result */;
return modifier.apply(back); //apply our external modifier
}
}
//With our old 'c'
double odds = c.chanceOfSuccess(d -> d * 2); //twice as likely!
There's so much more flexibility provided from the Function API in java 8, making complex problems like this incredibly simplified to write.
#John here is how I have approached a solution to your problem.
I used the case of MathOperations to make it simpler. I think first that I would be better to have the interface outside of SomeClass like:
public interface MathOperable {
public int mathOperation(int n1, int n2);
}
I created two examples of classes implementing this interface and one anonymous implementation inside SomeClass (I did an Add, Multiply and an anonymous "Substract")
public class Add implements MathOperable {
public int mathOperation(int n1, int n2) {
return n1 + n2;
}
public String toString() {
return "<addition>";
}
}
The overriding of toString() is simply for the purpose of giving more readability to the examples that I will show at the end of my post.
public class Multiply implements MathOperable {
public int mathOperation(int n1, int n2) {
// TODO Auto-generated method stub
return n1 * n2;
}
public String toString() {
return "<multiplication>";
}
}
Here is my SomeClass class, it contans a getRandomListOfOperations, where I simulate what happens when the click on the button is done
public class SomeClass {
private static MathOperable addition = new Add();
private static MathOperable multiplication = new Multiply();
// Anonymous substraction
private static MathOperable substraction = new MathOperable() {
public int mathOperation(int n1, int n2) {
// TODO Auto-generated method stub
return n1-n2;
}
public String toString() {
return "<substraction>";
}
};
public List<MathOperable> getRandomListOfOperations() {
// We put the methods in an array so that we can pick them up later randomly
MathOperable[] methods = new MathOperable[] {addition, multiplication, substraction};
Random r = new Random();
// Since duplication is possible whe randomly generate the number of methods to send
// among three so if numberOfMethods > 3 we are sure there will be duplicates
int numberOfMethods = r.nextInt(10);
List<MathOperable> methodsList = new ArrayList<MathOperable>();
// We pick randomly the methods with duplicates
for (int i = 0; i < numberOfMethods; i++) {
methodsList.add(methods[r.nextInt(3)]);
}
return methodsList;
}
public void contactSomeOtherClass() {
new SomeOtherClass(getRandomListOfOperations());
}
}
Now here is my SomeOtherClass (which may correspond to your Worker class)
public class SomeOtherClass<T extends MathOperable> {
Random r = new Random();
List<T> operations;
public SomeOtherClass(List<T> operations) {
this.operations = operations;
runIt();
}
public void runIt() {
if (null == operations) {
return;
}
// Let's imagine for example that the new result is taken as operand1 for the next operation
int result = 0;
// Here are examples of the web service own datas
int n10 = r.nextInt(100);
int n20 = r.nextInt(100);
for (int i = 0; i < operations.size(); i++) {
if (i == 0) {
result = operations.get(i).mathOperation(n10, n20);
System.out.println("Result for operation N " + i + " = " + result);
} else {
// Now let's imagine another data from the web service operated with the previous result
int n2 = r.nextInt(100);
result = operations.get(i).mathOperation(result, n2);
System.out.println("Current result for operation N " + i + " which is " + operations.get(i) +" = " + result);
}
}
}
}
I have a simple test class that contains a main to connect the two classes
public class SomeTestClass {
public static void main(String[] args) {
SomeClass classe = new SomeClass();
classe.contactSomeOtherClass();
}
}
Now a few examples of executions:
And another illustration!
I hope this could be helpful!
Okay, I'm going to be "that guy"... the one who understands the question but asks anyway to restate the problem because I think you are on the wrong path. So, bear with me: if you like what you see, great; if not, I understand.
Basically, you have a different intent/motivation/purpose than what "adapter" is suited for. The command pattern is a better fit.
But first, more generally, one of the goals of designing "elements of reusable software" (from the title of the original GOF design patterns book) is that you don't want to modify code when you add functionality; rather, you want to add code without touching existing functionality. So, when you have:
public class Toolbox {
public void hammer() { ... }
}
and you want to add a screwdriver to your toolbox, this is bad:
public class Toolbox {
public void hammer() { ... }
public void screwdriver() { ... }
}
Rather, ideally, all existing code would remain unchanged and you would just add a new Screwdriver compilation unit (i.e., add a new file), and a unit test, and then test the existing code for regression (which should be unlikely, since none of the existing code changed). For example:
public class Toolbox {
public void useTool(Tool t) { t.execute(); ...etc... }
}
public interface Tool { // this is the Command interface
public void execute() // no args (see ctors)
}
public Hammer implements Tool {
public Hammer(Nail nail, Thing t) // args!
public void execute() { nail.into(t); ... }
}
public Screwdriver implements Tool {
public Screwdriver(Screw s, Thing t)
public void execute() { screw.into(t); ... }
}
Hopefully it should become clear how to extend this to your example. The Worker becomes straight-foward list of Tools (or, for clarity, instead of "Tool" , just call it a "Command").
public class Worker {
public List<Command> actionList;
....
public void work() {
for(...) {
action.execute();
}
}
}
This pattern also allows for easy "undo" functionality and "retry", as well as memoization (caching results so they don't have to be re-run).
I have a class "Tool" and various subclasses like "Axe" oder "Hammer". Each kind of Tool(Axe, Hammer) has at least one method which is defined in the subclass. And there is a "Worker" class with a slot for one tool at the time that can be every tool.
Tool class:
public abstract class Tool {
private double durability;
public double getDurability() {
return durability;
}
public void setDurability(double durability) {
this.durability = durability;
}
}
Axe class:
public class Axe extends Tool {
public void chop() {
//chop some wood
}
}
Now to set one tool for the worker:
Tool tool = new Axe();
The problem is that when i call "axe." i get getDurability() and setDurability() but not chop().
abstract class Tool {
private double durability;
public double getDurability() {
return durability;
}
public void setDurability(double durability) {
this.durability = durability;
}
public void work(){
}
}
class Axe extends Tool {
#Override
public void work() {
this.chop();
}
public void chop() {
//chop some wood
}
}
If you want to call chop, you need to know that you have an Axe (not just any old Tool).
Then you can typecast:
Axe axe = (Axe) tool;
axe.chop();
If you are not sure if this is really an Axe, you can check first (but this is a bit of a design smell):
if (tool instanceof Axe){
Axe axe = (Axe) tool;
axe.chop();
}
You have to call after casting to Axe
((Axe)tool).chop();
But you have to check it before casting to avoid any Exception
if (tool instanceof Axe) {
((Axe)tool).chop();
}
Hey everyone I'm studying for a midterm exam and I'm studying the sample midterm from a previous semester, the answers are given but I'm trying to figure out how the answers came about. Question and answers below, I understand how he got "zero" but not the rest:
Write the 10-lines output of the program Bird.java shown below.
interface Silly {
public void narf();
public void poit(Silly s);
}
public class Bird implements Silly {
public static void main(String args[]) {
System.out.println("zero");
Silly s = new SillyBird(1);
Silly s2 = new Loony();
s.poit(s2);
s2.poit(s);
System.out.println("zymurgy");
}
public Bird() {
this(0);
System.out.println("zircon");
}
public Bird(int i) {
System.out.println("zanzibar");
}
public void narf() {
System.out.println("zort");
}
public void poit(Silly s) {
s.narf();
}
}
class SillyBird extends Bird {
public SillyBird() {
System.out.println("duchess");
}
public SillyBird(int i) {
super(i);
}
public void narf() {
System.out.println("drum");
super.narf();
}
}
class Loony extends SillyBird {
public Loony() {
System.out.println("stupendous");
}
public void narf() {
System.out.println("snark");
}
}
His answers are: zero
zanzibar
zanzibar
zircon
duchess
stupendous
snark
drum
zort
zymurgy
interface Silly {
public void narf();
public void poit(Silly s);
}
public class Bird implements Silly {
public static void main(String args[]) {
System.out.println("zero"); // 1. zero
Silly s = new SillyBird(1); // 2. zanzibar
Silly s2 = new Loony(); // 3. zanzibar zircon duchess stupendous
s.poit(s2); // 4. snark
s2.poit(s); // 5. drum zort
System.out.println("zymurgy");// 6. zymurgy
}
public Bird() {
this(0);
System.out.println("zircon");
}
public Bird(int i) {
System.out.println("zanzibar");
}
public void narf() {
System.out.println("zort");
}
public void poit(Silly s) {
s.narf();
}
}
class SillyBird extends Bird {
public SillyBird() {
System.out.println("duchess");
}
public SillyBird(int i) {
super(i);
}
public void narf() {
System.out.println("drum");
super.narf();
}
}
class Loony extends SillyBird {
public Loony() {
System.out.println("stupendous");
}
public void narf() {
System.out.println("snark");
}
}
I hope this helps... I think the most important one to understand is number 3 where you have implicit super() calls.
WHat you probably don't get is that whan a constructor doesn't explicitely invoke super(), then the compiler adds a super() call anyway, to the very beginning of the constructor. So,
public SillyBird() {
System.out.println("duchess");
}
is equivalent to
public SillyBird() {
super();
System.out.println("duchess");
}
Add the super() calls at the very beginning of the constructors which don't have one, then follow the calls, and you'll find the answer. For example, the call to
Silly s2 = new Loony();
calls the Loony constructor, which calls super(). So the SillyBird no-arg constructor is called, which first calls super(). So the Bird no-arg constructor is called, which calls this(0). SO the 1-arg constructor of Bird is called, etc.
If you don't understand how 'he got the rest' - you need to read a basic tutorial on objects, classes, and interfaces. Start with the one provided by Oracle. In a nutshell, the print statements occur in the same order the constructors and override methods are being executed. For example, the second word 'zanzibar' is printed because the
public SillyBird(int i) {
super(i);
}
constructor is invoked Silly s = new SillyBird(1);, which invokes:
public Bird(int i) {
System.out.println("zanzibar");
}
via the super(i) invocation.
Now try to reason through how the second 'zanzibar' print occurs.