Sorry I really didn't know how to title the question, here's the problem...
I have an interface and multiple classes that implement the interface. The implementation of some of the methods in the interface are exactly the same in every implementing class. I feel like there should be a way to simplify this so I don't have to write the same code every time. Example:
public interface Foo {
String getName();
}
public class FooImpl1 implements Foo {
private String name = "foo name1";
public String getName() {
return name;
}
}
public class FooImpl2 implements Foo {
private String name = "foo name2";
public String getName() {
return name;
}
}
So to break down..
is there a way to put the code for getName in one place and each class has it's own name variable?
is there a way to make getName static so I don't have to create a new instance
Have better ideas?
A class can implement multiple interfaces and many classes can implement the same interface. A class can implement multiple interfaces and many classes can implement the same interface. Final method can't be overridden. Thus, an abstract function can't be final.
No, its an error If two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously. According to JLS (§8.4. 2) methods with same signature is not allowed in this case.
C# allows the implementation of multiple interfaces with the same method name.
C# allows that a single class can implement multiple interfaces at a time, and also define methods and variables in that interface.
Use an abstract class and initialize the field in the constructor:
public abstract class Foo {
protected String name;
String getName() {
return name;
}
}
public class FooImpl1 extends Foo {
public FooImpl1 () {
name = "foo name1";
}
}
public class FooImpl2 extends Foo {
public FooImpl1 () {
name = "foo name2";
}
}
JB Nizlet pointed out that it would be cleaner to do something like this:
public abstract class Foo {
protected String name;
public Foo(String newName) {
name = newName;
}
String getName() {
return name;
}
}
And then call super("foo name 1")
in the subclasses.
As @Peter Lawrey said, if you already have an interface or want one for some other reason:
public interface IFoo {
String getName();
}
public abstract class Foo implements IFoo {
protected String name;
String getName() {
return name;
}
}
You could take a very simple approach:
public interface Foo {
String getName();
}
public class Named implements Foo {
String name;
public String getName() {
return name;
}
}
public class FooImpl1 extends Named {
{name = "foo name1";}
}
public class FooImpl2 extends Named {
{name = "foo name2";}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With