Calling an overridable method in constructor - java

I have multiple different implementations of an object, which implement this custom interface I made called Board.
Board contains a method that looks like the following
public void ConvertFromString(String formattedString);
Each object implementing Board calls ConvertFromString() in its constructor.
Looks like the following.
public void BoardImpl1 implements Board
{
public Board(string B)
{
ConvertFromString(b);
}
public void ConvertFromString(String formattedString)
{
//do some parsing on string and set up the BoardImpl properties
}
}
ConvertFromString being public causes a warning, so one of the workarounds that I found would be to make BoardImpl final. Is there a better way to approach this?

//do some parsing on string and set up the BoardImpl properties
The method should be responsible to convertFromString only.
1) Make the method final
public class BoardImpl implements Board{
public void final convertFromString(String formattedString)
{
//do some parsing on string and set up the BoardImpl properties
}
}
2) Solution make an abstract class and call in superClass constructor so you don't have to call in each subclass BUT don't use properties from subclass cause they aren't intilized.
public abstract class AbstractBoard implements Board{
public AbstractBoard(String s){
convertFromString(s);
}
}
3) And My preferred one make something with composition
public class Client {
private Board board;
public Client(String s){
board.convertFromString(s);
}
public void setBoard(Board board){
this.board = board;
}
}
Then in the board you can delegate responsability of deciding wich Board you should use to a factory or if it has no state a FlyweightFactory

Does ConvertFromString really belong in the Board interface to begin with? What if you had a board that initialized its properties a different way? I would consider refactoring out the board class if you can.
public class Board {
public Board(Properties properties) {...}
}
I think the reason you're having trouble setting this up without calling the public ConvertFromString method is because the design is a little off. The ConvertFromString makes assumptions about the implementation of it.

There is compile error in your code
I could not get a compile warning with following code
public interface Board {
public void ConvertFromString(String formattedString);
}
public class BoardImpl1 implements Board {
public BoardImpl1(String b) {
ConvertFromString(b);
}
public void ConvertFromString(String formattedString) {
//bla bla
}
}

Related

Appropriate design pattern for choosing between two classes which do not have similar functions

I have 2 classes Workflow1.java and Workflow2.java. At a class Selection.java I want to be able to choose between instantiating one of the 2 classes as a static member however I cannot implement the factory pattern as Workflow1 and Workflow2 cannot be subclasses since their methods are not the same. Although they achieve the same end result they do so by doing entirely different operations. Is there a design pattern for this scenario?
Example: If the classes were WalkHelper.java and DriveHelper.java, the methods you need in each are entirely different but what you are trying to achieve is the same - reach a destination. I haven't created walk() and drive() as methods as WalkHelper.java has existed in our code base and I'm adding DriveHelper.java to it.
It sounds like you can still use a Factory pattern but you may have to use an Adaptor to make them equal... Without knowing more, it's a pretty difficult question to answer.
interface IFactory {
void run();
String getResult();
}
class Workflow1Adapter implements IFactory {
Workflow1 wf1 = new Workflow1();
public void run() {
wf1.doSomething();
}
public String getResult() {
wf1.doAnother();
}
}
class Workflow2Adapter implements IFactory {
Workflow2 wf2 = new Workflow2();
public void run() {
wf2.doThatThing();
}
public String getResult() {
wf2.doReturn();
}
}
class Workflow1 {
public void doSomething() {}
public String doAnother() {}
}
class Workflow2 {
public void doThatThing() {}
public String doReturn() {}
}

C# equivalent to implement interface inside super keyword in Java [duplicate]

I am not sure how am I suppose to go about my question. It is about Android can Instantiate Interface. I am trying to do in C#. Now I am pretty sure that the rules for both Java and C# is you can't create an Instance of abstract and Interface as being said.
But I would really like to know how Android does this practice.
In Android you can do this.
public interface Checkme{
void Test();
void Test2();
}
public void myFunc(Checkme my){
//do something
}
// Now this is the actual usage.
public void Start(){
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
}
Actually once you press Enter on new Checkme() You will automatically get the Override methods of the Interface. Like auto Implement method of an Interface in C#.
I hope my question make sense.
C# doesn't support anonymously auto-implemented interfaces because it has delegates:
public void Foo(Func<string> func, Action action) {}
// call it somewhere:
instance.Foo(() => "hello world", () => Console.WriteLine("hello world"));
With delegates you can fill the gap and it can be even more powerful than implementing interfaces with anonymous classes.
Learn more about delegates.
This is an Anonymous Class:
public void Start(){
myFunc(new Checkme() {
#Override
public void Test() {
}
#Override
public void Test2() {
}
});
}
An anonymous class is an unnamed class implemented inline.
You could also have done it using a Local Class, but those are rarely seen in the wild.
public void Start(){
class LocalCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
myFunc(new LocalCheckme());
}
These both have the advantage that they can use method parameters and variables directly, as long as they are (effectively) final.
As a third option, you could do it with an Inner Class.
private class InnerCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
public void Start(){
myFunc(new InnerCheckme());
}
An inner class cannot access method variables (obviously because it's outside the method), but can be used by multiple methods.
Any local values from the method can however be passed into the constructor and stored as fields of the inner class, to get the same behavior. Just requires a bit more code.
If the inner class doesn't need access to fields of the outer class, it can be declared static, making it a Static Nested Class.
So, all 3 ways above a very similar. The first two are just Java shorthands for the third, i.e. syntactic sugar implemented by the compiler.
C# can do the third one, so just do it that way for C#.
Of course, if the interface only has one method, using a Java lambda or C# delegate is much easier than Anonymous / Local / Inner classes.
If I understand correcly, you're defining a class that implements an interface, and when you specify that the class implements an interface, you want it to automatically add the interface's methods and properties.
If you've declared this:
public interface ISomeInterface
{
void DoSomething();
}
And then you add a class:
public class MyClass : ISomeInterface // <-- right-click
{
}
Right-click on the interface and Visual Studio will give you an option to implement the interface, and it will add all the interface's members to the class.
you mean something like this?
pulic interface Foo{
void DoSomething();
}
public class Bar : Foo {
public void DoSomething () {
//logic here
}
}
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
You're passing into myFunc() something that is called an anonymous class. When it says "new Checkme() { .... }", it is defining an anonymous implementation of the Checkme interface. So, it's not an instance of the interface itself, just an instance of a type that implements it.
In C# anonymously implemented classes for Interface are not auto generated just like in java, you need to follow the below procedure to workout.
public class MyClass {
public void someMethod (string id, IMyInterface _iMyInterface) {
string someResponse = "RESPONSE FOR " + id;
_iMyInterface.InterfaceResponse (someResponse);
}
}
public interface IMyInterface {
void InterfaceResponse (object data);
void InterfaceResponse2 (object data, string x);
}
public class MyInterfaceImplementor : IMyInterface {
private readonly Action<object> actionname;
private readonly Action<object, string> actionInterfaceResponse2;
public MyInterfaceImplementor (Action<object> InterfaceResponse) {
this.actionname = InterfaceResponse;
}
public MyInterfaceImplementor(Action<object> interfaceResponseMethod, Action<object, string> interfaceResponseMethod1) {
this.actionname = interfaceResponseMethod ?? throw new ArgumentNullException(nameof(interfaceResponseMethod));
this.actionInterfaceResponse2 = interfaceResponseMethod1 ?? throw new ArgumentNullException(nameof(interfaceResponseMethod1));
}
public void InterfaceResponse (object data) {
this.actionname (data);
}
public void InterfaceResponse2(object data, string x) {
this.actionInterfaceResponse2(data, x);
}
}
Gist Source : https://gist.github.com/pishangujeniya/4398db8b9374b081b0670ce746f34cbc
Reference :

Is it possible to make a reference to an abstract class method in a class method that doesn't extend it?

I'm taking a tutorial on building a simple behavior Ai. It's 'brain' class is abstract and contains states as in "running","success","failure". Now in the my ai unit - droid class i have a method to start the brain of the droid up.
public void update(){
if(Routine.getState()==null){
Routine.start();
}
Routine.act(this, board);
}
Now this isn't possible in java because it's a static reference to a non-static method.
The routine abstract class that i'm trying to reference to here goes like this :
public abstract class Routine {
public enum RoutineState{
Success,
Failure,
Running
}
protected RoutineState state;
protected Routine() { }
public void start(){
this.state = RoutineState.Running;
}
public abstract void reset();
public abstract void act(droid droid, board board);
public void succed(){
this.state = RoutineState.Success;
}
public void Fail(){
this.state = RoutineState.Failure;
}
public boolean isSuccess(){
return state.equals(RoutineState.Success);
}
public boolean isFailure(){
return state.equals(RoutineState.Failure);
}
public boolean isRunning(){
return state.equals(RoutineState.Running);
}
public RoutineState getState(){
return state;
}
}
I've tried copying the method to one of the classes that extends the Routine, but that doesn't work either the same problem comes up.
The static requirement is especially difficult on start() and act() that contain this. and are initializers.
I can only make the method update() like it is, in the routine where i initialize the droid and the board it will be acting on - but i don't see this quite like the solution i'd like to have.
For sure, you can reference an abstract class and call its abstract classes, but the object you exactly reference should be an extender of the abstract class.
For example, create a list of different objects, all extending one abstract class.
public abstract class ExAbstract { public abstract void abstractmethod() {...} }
public class ExampleA extends ExAbstract { #Override... }
public class ExampleB extends ExAbstract { #Override... }
...
List<ExAbstract> list = new ArrayList<>();
list.add(new ExampleA());
list.add(new ExampleB());
...
And then, you can call abstract method on it.
for (ExAbstract test : list){
test.abstractmethod();
}
(Or Java 8)
list.forEach(ExAbstract::abstractmethod);
But if object wasn't extending abstact, and it was abstract itself, it would give an error.
EDIT: In your case, with Routine class, you should make a constructor for it, and then make a new object. (I see you have a constructor already...) If you want to use a method without creating an object, use static
In Routine.java:
public Routine(ExampleArg a){
this.a = a;
}
In your Routine call:
Routine r = new Routine(a);
r.start();

How to Invoke a specific implemented class of a Interface

What I try to accomplish is to invoke the Interface of a specific class.
I use a Enum to fill in the .class and to get the Interface of that Class.
So how can I return the interface?
I would like to avoid reflection if possible.
Thanks in advance.
public interface GameInterface {
void start();
void sop();
}
public enum Game{
MINESWEEPER(MineSweeper.class),
MARIO(Mario.class);
private Class c;
public Game(Class c) {
this.c = c;
}
public GameInterface getGameInterface() {
// return Interface of the class
// So I can call for instance MINESWEEPER.getGameInterface().start()
// At this momement I use return:
// ((GamemodeInterface)this.c.getDeclaredMethod("getInstance", new Class[0]).invoke(null, new Object[0]));
// *MineSweeper and Mario are Singleton, thats why getInstance
}
}
Clarification:
The main goal is to acces Start() and Stop() methods at MineSweeper and Mario class.
The usage should be something like: MINESWEEPER.getGameInterface().start()
But at this moment I don't know a solid solution to get the Interface with knowing of the .class.
A better idea:
Implement GameInterface to each Game of your class with implying name of your choice.
Declare enum with abstract function createGame and return with the instance of the Game class you are expecting with implementation of this createGame function to each enum constant:
class MineSweeper implements GameInterface
{
// your code
}
class Mario implements GameInterface
{
// your code
}
public enum GameType
{
MINESWEEPER
{
public GameInterface createGame()
{
return new MineSweeper();
}
},
MARIO
{
public GameInterface createGame()
{
return new Mario();
}
}
public abstract GameInterface createGame();
}
If you intended to use singleton pattern, although i could not be so sure from your question but as #GaborSch has suggested: you could make use of MineSweeper.getInstance() function inside the createGame() of enum constants. However, try thinking to use an enum while implementing a Singleton too, as is suggested in Effective Java book with detail explanation.

How to set up different parameter in a Composite Pattern?

for my develop i want to use the component-pattern because a component is part of another component.
But there is one problem. The components need different parameters in the run-function (which must be implement).
Does someone have a idea how to realize it?
Example:
public abstract class componsite{
Componente(){...}
public void run(Object object1){......}
}
public class firstComponent extends composite{
....
public void run(Object object1){......}
#Override
}
public class secondComponent extends composite{
....
#Override
public void run(Object object1,Different Object object2){......}
}
Greetz
Use Java's Varargs as part of the Composite interface
public class secondComponent extends composite{
....
#Override
public void run(Object... object){......}
}
Consider using the Visitor pattern. This allows for an elegant strongly typed solution that avoids type checking using instanceof or downcasting.
public interface ComponentVisitor {
void visitFirstComponent(FirstComponent fc);
void visitSecondComponent(SecondComponent sc);
}
public class ComponentVisitorImpl implements ComponentVisitor {
public void visitFirstComponent(FirstComponent fc) {
fc.firstComponentSpecifiedMethod(a, b, c);
// Make a call *back* to FirstComponent passing in appropriate parameters.
}
}
Then within each Component's run() method you simply call the relevant visitor method which will then make a call back into the component with the relevant parameters; e.g.
public class FirstComponent extends Component {
public void run(ComponentVisitor cv) {
cv.visitFirstComponent(this);
}
}
The drawback of this approach is that the logic can be difficult to follow.

Categories