What is the class that declaring method of another class - java

I remember on my previous web development job that they have something like this:
sampleClassBean.java:
public class sampleClassBean
{
public String doSomeStrings(String a, String b){}
public Int doSomeInt(Integer i, integer j){}
public Boolean doSomeBoolean(Boolean result){}
}
and then there's sampleClassBeanImpl
public class sampleClassBeanImpl
{
public String doSomeStrings(String a, String b)
{
//do some process
return "";
}
public Integer doSomeInt(Integer i, Integer j)
{
//do some process
return 0;
}
public Boolean doSomeBoolean(Boolean result)
{
//do some process
return false;
}
}
For what I understand is that, there's 2 class, 1st class that declare methods, now 2nd class's methods will depend on what is declared on the 1st class. If the 2nd class create a method that is not declared in 1st class there will be an error. Hope you understand what i'm saying.
What I need to know is what exactly that? What do you call that process? How to do that? What are the benefits of doing that? Is it a good programming practice?

Yes it is good practice, you are talking about interfaces:
Java includes a concept called interfaces. A Java interface is a bit like a class, except a Java interface can only contain method signatures and fields. An Java interface cannot contain an implementation of the methods, only the signature (name, parameters and exceptions) of the method.
The interface:
public interface SampleClassBean {
public String doSomeStrings(String a, String b);
public int doSomeInt(int i, int j);
public Boolean doSomeBoolean(Boolean result);
}
And the implementation:
public class SampleClassBeanImpl implements SampleClassBean {
#Override
public String doSomeStrings(String a, String b) {
return null;
}
#Override
public int doSomeInt(int i, int j) {
return 0;
}
#Override
public Boolean doSomeBoolean(Boolean result) {
return null;
}
}
Interfaces are really useful because unlike other languages Java doesn't support multiple inheritance but you can implement all the interfaces you wish!
Have a read of this it'll help you understand interfaces and when to implement them.

Related

Reuse validation method. Convert object

I have two similar class objects. I have a couple of methods for the first class object wich I also want to reuse for my second class object but I'm not sure how and I don't want to write duplicate methods.
I extracted and simplified an example to show how i think.
first class
public class FirstClass {
int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
...
}
Second class
public class SecondClass {
int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
...
}
Third class
public class Main {
public static void main(String[] args) {
FirstClass firstClass = new FirstClass();
firstClass.setNumber(5);
SecondClass secondClass = new SecondClass();
secondClass.setNumber(5);
numberIsFive(firstClass);
numberIsFive(secondClass);
}
public void numberIsFive(Object myObject){
if(myObject instanceof FirstClass){
myObject = (FirstClass)myObject;
}else if(myObject instanceof SecondClass){
myObject = (SecondClass)myObject;
}
if(myObject.getNumber() == 5){
System.out.println("is five");
}else{
System.out.println("is not five");
}
...
}
}
and no numberIsIFive(firsclass.getNumber()) is not an option since the methods I use have much more validations.
thanks in advance
For this case that might be "over-engineering", but in general you would look towards composition here, like:
interface IntValueHolder {
int getNumber();
void setNumber(int value);
}
class IntValueHolderImpl implements IntValueHolder { ...
And then you would "drop" the code that you currently have in both of your classes, and instead, both classes would (somehow) have an instance of IntValueHolder.
In your case, it might be more appropriate to simple have your two classes implement that "common" interface IntValueHolder - to at least avoid that repeated instanceof calls and downcast (down to a specific class).
Edit: of course, another option would be to use inheritance here - make your two classes derive from some base class that provides this behavior. But using inheritance just to avoid code duplication is most of the time a bad idea. Classes inherit from each other because that makes "sense" in the underlying model, not to save a line of code.
Before continuing I recommend you to read about it and other object oriented programming concepts by yourself.
Focusing on this particular case, you should create a base class such as
public class BaseClass {
int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
Which includes all common fields and methods of your FirstClass and SecondClass. Then remove those methods from your two current classes, and just create them as public class FirstClass extends BaseClass to give them BaseClass functionality.
Finally, you'd have to change your validation method, to only accept objects that belong to your base class by making it like this public void numberIsFive(BaseClass myObject) (as a general rule you'll have much less errors by accepting a specific class in a method, rather than accepting any old object).
Edit: Other answerers are correct and Inheritance is also a valid solution. Which one you use would depend on what makes more sense in the context of your application.
You should create an interface and apply it in both classes, then make your validation method receive an interface instead of an Object
Example:
public interface Number {
int get();
void set(int n);
}
Then your classes will look like this:
public class FirstClass implements Number {
int number;
#Override
public int get() {
return number;
}
#Override
public void set(int n) {
this.number = n;
}
}
And your validation method receives a Number:
public void numberIsFive(Number myNumber){
...
}

A java method with both variable return type and variable input arguments

I have an abstract java class "BaseOperation". This class only has a single abstract method:
public abstract T execute()
{
...
return T;
}
Subclasses of BaseOperation must implement this method:
public class GetUsersOperation extends BaseOperation<GetUsersResponse>
{
...
#Override
public GetUsersResponse execute()
{
...
return GetUsersResponse;
}
}
This is a great way to put all common "operation" logic in the BaseOperation class, but still have every concrete subclass's execute() method have a different return type.
Now I need to change this structure to allow the execute() methods to have a variable amount of arguments. For example, one concrete subclass would require:
execute(String, int)
and another would need:
execute(Date, Date, String)
This is tricky, because the execute method is declared in the base class. Simply overloading the execute methods in the base is not ideal. Firstly, the amount of overloads would be huge. Secondly, every subclass will only ever use one of the execute methods, what's the point of all the others?
The (in my opinion) easiest solution would be to declare the execute method with varargs:
execute(Object... arguments)
And then downcast all arguments in the subclasses:
execute(Object... arguments)
{
String s = (String) arguments[0];
...
}
Obviously this has 2 major downsides:
Reduced performance because of all the downcasting operations
Calling the execute() methods is no longer strictly typed because any amount of objects can be passed witout compiler warnings.
Are there patterns or other solutions that could don't have these disadvantages?
You could use a bean holding the parameters:
public interface BaseOperation<T, U> {
T execute(U input);
}
public class GetUsersOperation implements BaseOperation<GetUsersResponse, UserInput> {
#Override
public GetUsersResponse execute(UserInput input) {
Date date = input.getDate();
return new GetUsersResponse(date);
}
}
Your abstract class only has one single abstract method: better use an interface. You can implement several interfaces while you can extend only one class.
As already said, the common approach for solving your issue is using a bean holding parameters. But here is another solution, based on a builder approach:
public interface BaseOperation<T> {
public T execute();
}
public class AddOperation implements BaseOperation<Integer> {
private int a, b;
public void setA(int arg){
a = arg ;
return this;
}
public void setB(int arg){
b = arg;
return this;
}
#Override
public Integer execute() {
return a+b ;
}
}
And then use it like this :
new AddOperation().setA(1).setB(2).execute();
You can mix required and optional parameters in this way:
public class MultipleAddOperation implements BaseOperation<Integer> {
private int sum ;
public MultipleAddOperation(int requiredInt){
sum = requiredInt;
}
public void add(int optionalInt){
sum += optionalInt ;
return this;
}
#Override
public Integer execute(){
return sum;
}
}
And so:
new MultipleAddOperation(5).add(1).add(2).execute();

Is it convenient to use java.lang.Void for classes that doesn't return anything?

I'm developing a clustering framework and I have the following interface
in order to provide a way to execute a piece of code on another node in the cluster:
interface Operation<V> {
V run();
int getService();
}
However, the user may not care about the result of an operation.
In this case I need to provide a convenient way for them. I have two options:
I can tell them to use java.lang.Void as parameter and check the return type in remote server and return the result if the generic type is not Void:
new Operation<Void> {
public Void run() {
//
return null;
}
public int getService() { return 1; }
}
However, even if they use java.lang.Void,
they still need to return something in run method so
it might not be a good way to do something like that.
Also I can create another interface that doesn't not return anything.
However, now we have two types and I'm afraid it can be much for complex than the first way.
interface FireAndForgetOperation {
void run();
int getService();
}
Which way do you think is more convenient?
I think your first approach is convenient. It is used inside some java libraries. One example is the Callback interface in JavaFX (https://docs.oracle.com/javafx/2/api/javafx/util/Callback.html).
Code that needs to use a callback and does want any returned value declares the callback as:
CallBack<SomeClass, Void> myCallBack;
And in the call method you return null;
I would definitely do something like this to avoid exposing something that doesn't have to be:
public interface Operation<V> {
V run();
public int getService();
}
abstract public class VoidOperation implements Operation<Void> {
public final Void run() {
runVoid();
return null;
}
abstract public void runVoid();
abstract public int getService();
}
Usage :
new Operation<String>() {
public String run() {
return null;
}
public int getService() { return 1; }
};
new VoidOperation() {
public void runVoid() {
}
public int getService() { return 1; }
};

Tips: wrapping class in java in order to add new methods

I would like to ask you some tips about this java scenario:
I have a simple interface called Sequence that performs some basic operation. Now I would like to implement some additional methods in a separate class, called SequenceWrapper, that implements the Sequence defined above. Here is some example code that looks like my real code:
public interface Sequence {
public void methodOne();
public int methodTwo();
}
public abstract class SequenceWrapper implements Sequence {
private wrappedSequence = null;
public SequenceWrapper(Sequence sequence){
this.wrappedSequence = sequence;
}
public void methodOne(){
wrappedSequence.methodOne();
}
public int methodTwo(){
return wrappedSequence.methodTwo();
}
}
public class ConcreteWrapper extends SequenceWrapper {
public ConcreteWrapper(Sequence sequence){
super(sequence);
}
// Just an example
public int addMethodOne(){
int a = super.methodTwo();
return a + 3;
}
}
Now if I want to implements a class with another method (say 'addMethodTwo()') I can simply extends the 'ConcreteWrapper' class and add only the new method:
public class ConcreteWrapperTwo extends ConcreteWrapper {
public ConcreteWrapperTwo(Sequence sequence){
super(sequence);
}
public int addMethodTwo(){
int a = super.methodTwo();
return a + 30;
}
}
What do you think? Is this code correct or it's preferable another strategy??
Thanks in advance
First, your private wrappedSequence = null; has no type.
I suppose you meant private Sequence wrappedSequence = null;
Second, in your example you will never be able to instantiate any of the classes, since all of them receive another Sequence in the constructor and there is no way of create the first instance of Sequence.
Third, composition over inheritance is a good approach, if you really need it. Usually you wrap an object when you need to hide or protect the access to the wrapped object. In your case, within the wrapper you are exposing all of the methods of the wrapped object. You then create new methods that will affect the wrapper object, but not the wrapped one.
What you probably need is just a normal inheritance scenario:
I would like to walk you through you a breakdown for this Java scenario:
I have a simple interface called Sequence that performs some basic operation. Now I would like to implement some additional methods in a separate class, called SequenceWrapper that implements the Sequence as defined above. Here is some example code to explain what I mean:
public interface Sequence {
public void methodOne();
public int methodTwo();
}
public abstract class AbstractSequence implements Sequence {
public SequenceWrapper( ){ }
public void methodOne(){
//basic behavior here
}
public int methodTwo(){
//basic behavior here
}
}
public class ConcreteSequence extends AbstractSequence {
public ConcreteSequence ( ){
super( );
}
// Just an example
public int addMethodOne(){
int a = methodTwo();
return a + 3;
}
}
public class ConcreteSequenceTwo extends AbstractSequence {
public ConcreteSequenceTwo( ){
super( );
}
public int addMethodTwo(){
int a = methodTwo();
return a + 30;
}
}

Enforcing dynamic polymorphic calls with general parent type input arguments

I am trying to use polymorphism to enable different processing of an object based on its class, as follows:
public class GeneralStuff {
private int ID;
}
public class IntStuff extends GeneralStuff {
private int value;
public void setValue(int v)
{
value = v;
}
public int getValue()
{
return value;
}
}
public class DoubleStuff extends GeneralStuff {
private double value;
public void setValue(double v)
{
value = v;
}
public double getValue()
{
return value;
}
}
public class ProcessStuff {
public String process(GeneralStuff gS)
{
return doProcess(gS);
}
private String doProcess(IntStuff i)
{
return String.format("%d", i.getValue());
}
private String doProcess(DoubleStuff d)
{
return String.format("%f", d.getValue());
}
}
public class Test {
public static void main(String[] args)
{
IntStuff iS = new IntStuff();
DoubleStuff dS = new DoubleStuff();
ProcessStuff pS = new ProcessStuff();
iS.setValue(5);
dS.setValue(23.2);
System.out.println(pS.process(iS));
System.out.println(pS.process(dS));
}
}
This, however, doesn't work, because calling doProcess(gS) expects a method with a signature doProcess(GeneralStuff gS).
I know I could just have two exposed polymorphic process methods in the ProcessStuff class, but the actual situation won't allow it because I'm working within the constraints of an existing library mechanism; this is just a contrived example for testing.
I could, of course, define process(GeneralStuff gS) as
public String process(GeneralStuff gS)
{
if (gS instanceof IntStuff)
{
return doProcess((IntStuff) gS);
}
else if (gS instanceof DoubleStuff)
{
return doProcess((DoubleStuff) gS);
}
return "";
}
which works, but it seems that I shouldn't have to do that (plus, the Programming Police would skewer me for using instanceof in this way).
Is there a way that I can enforce the polymorphic calls in a better way?
Thanks in advance for any help.
The type of dynamic dispatch you are looking for is not possible in Java without using reflection. Java does its linking at compile time based on the declared type (so even though a method is overloaded, the actual method invoked is based on the declared type of the variable not the runtime type).
So you are left with either using instanceof as you propose, using reflection, or putting the process methods in the objects themselves (which is the "oop" way to do it, but is often not suitable or advisable).
One potential alternative is to create a map of processing objects by class, eg:
Map<Class<? extends GeneralStuff>,Processor> processors;
public String process(GeneralStuff stuff)
{
Processor processor = processors.get(stuff.getClass());
if (processor != null)
{
return processor.process(stuff);
}
}
public interface Processor
{
public String process(GeneralStuff stuff);
}
public class IntegerProcessor implements Processor
{
public String process(GeneralStuff stuff)
{
return String.format("%i",((IntegerStuff) stuff).getValue());
}
}
However, for your specific example, String.format takes objects as the parameters, so you could avoid this whole issue by having getValue and getFormatString methods in GeneralStuff which are overriden in the specific subclasses.
You are actually on the right track, you indeed need to use reflection in this case. What you are looking for is sort of double dispatch, because you want the dispatch to be done on the dynamic type of the stuff parameter.
This type of switching-on-dynamic-type is not as rare as you think. See for example this javaworld tipe, which reflects on the visitor pattern
The compiler complains for good reason. There is no guarantee that your GeneralStuff object is an IntStuff or a DoubleStuff. It can be a plain GeneralStuff or any other extension of GeneralStuff, which is a case you also did not cover in your process method with the instanceof (unless returning the empty String was the desired behavior).
Is it not possible to move that process method into the GeneralStuff class and override it in the extensions ?
Another possible solution is to have a sort of composite ProcessStuff class in which you plug a IntStuffProcess, DoubleStuffProcess, ... instance . Each of those instances will still have the instanceof check to decide whether they can handle the GeneralStuff object passed to them, but this is at least more scalable/maintainable then one big instanceof construct
Perhaps, it's better to have overloaded process method in ProcessStuff:
public class ProcessStuff {
private String process(IntStuff i) {
return String.format("%d", i.getValue());
}
private String process(DoubleStuff d) {
return String.format("%f", d.getValue());
}
}
Define an GeneralStuff as an abstract class, with a doProcess method (abstract) which is filled in in the inheriting classes. This way you avoid all problems with instanceof values and such. Or you can do what is suggested by βнɛƨн Ǥʋяʋиɢ, but then you still would have to define an overload for each specific class, whereas in mine you just call it directly.
So my suggestion would be:
public abstract class GeneralStuff {
private int ID;
public abstract String process();
}
public class IntStuff extends GeneralStuff {
private int value;
public void setValue(int v)
{
value = v;
}
public int getValue()
{
return value;
}
#override
public String process(){
return String.format("%d", getValue());
}
}
public class DoubleStuff extends GeneralStuff {
private double value;
public void setValue(double v)
{
value = v;
}
public double getValue()
{
return value;
}
#override
public String process(){
return String.format("%f", getValue());
}
}
public class Test {
public static void main(String[] args)
{
IntStuff iS = new IntStuff();
DoubleStuff dS = new DoubleStuff();
ProcessStuff pS = new ProcessStuff();
iS.setValue(5);
dS.setValue(23.2);
System.out.println(iS.process());
System.out.println(dS.process());
}
}

Categories