In: Computer Science
for java!!
Make a public class Value that provides a static method named test. test takes a single int argument and returns an anonymous object that implements the following Absolute interface:
public interface Absolute {
int same();
int opposite();
}
--------------------------------------------------------------------------
The returned object should implement same so that it returns the passed int as it is, and opposite so that it returns the passed int as the int * -1. For example
Absolute first = Value.test(-90)
Absolute second = Value.test(32)
System.out.println(first.same()); // prints -90.
System.out.println(first.opposite()); // prints 90.
System.out.println(second.same()); // prints 32.
System.out.println(second.opposite()); prints -32.
--------------------------------------------------------------------------
Please continue what I have started:
public class Value {
public static Absolute test(int input) {
I’m not too sure how to continue. I tried
new Value() {
public int same() {
return input;
but it didn’t work. please help in the simplest form of code possible, i am a beginner java student
Explanation:I have continued your code and have implemented the test method to return the anonymous Absolute object. It has the main method which also shows the output of the program, please find the image attached with the answer.Please upvote if you liked my answer and comment if you need any modification or explanation.
//Absolute
public interface Absolute {
int same();
int opposite();
}
//Value class
public class Value {
public static Absolute test(int input) {
return new Absolute() {
@Override
public int
same() {
return input;
}
@Override
public int
opposite() {
return -input;
}
};
}
public static void main(String[] args) {
Absolute first =
Value.test(-90);
Absolute second =
Value.test(32);
System.out.println(first.same());
// prints -90.
System.out.println(first.opposite()); // prints 90.
System.out.println(second.same());
// prints 32
System.out.println(second.opposite());// prints -32.
}
}
Output: