I‘m quite struggling by defining an abstract method in an interface. Why? In each class, related to this interface one method called “getInstance” has to be implemented. These methods returns the actual used instance.
So how do I define the abstract method in an interface for different classes?
public interface MyInterface {
public <<here is my question>> getInstance();
}
public class Class1() implements MyInterface {
public Class1 getInstance() {
return this;
}
}
public class Class2() implements MyInterface {
public Class2 getInstance() {
return this;
}
}
Please see my comment, it seems unlikely you really want to do this.
You can do what Khan Saab pointed out: Have getInstance's return type be MyInterface. But that won't work if you need to access features of Class1 or Class2 that aren't part of the interface.
You can do something like this with generics:
public interface MyInterface<T> {
public T getInstance();
}
public class Class1 implements MyInterface<Class1> {
public Class1 getInstance() {
return this;
}
}
public class Class2 implements MyInterface<Class2> {
public Class2 getInstance() {
return this;
}
}
But you couldn't (for instance) have an array of MyInterface and use a mix of Class1 and Class2 in it (without instanceof and casting).
All of which probably means you want to do something else.
I think you might find the idea of Generics useful:
For example:
Interface
public interface TestWithGenerics<T> {
public T getInstance();
}
Implementation
public class TestImplementation implements TestWithGenerics<TestImplementation> {
#Override
public TestImplementation getInstance() {
return this;
}
}
However, as the comments said, this all feels a bit funny. I find singletons to be a code smell. But I'm not sure what your requirements are, and I hope this helps.
As both the classes implement the interface MyInterface hence object of each class will be of type MyInterface.
public interface MyInterface{
public MyInterface getInstance();
// ....other methods
}
public class Class1 implements MyInterface{
#override
public MyInterface getInstance(){
return this;
}
//... other code
}
public class Class2 implements MyInterface{
#override
public MyInterface getInstance(){
return this;
}
//... other code
}
awesome :-)
finally I implemented the solution from “T.J. Crowder”. It works fine. Many many thanks to all of you. You gave me very interested hints on my road to create “better” code……
Related
Here's My code:
public interface Baseinterface {}
abstract class Interface1 implements Baseinterface{}
abstract class Interface2 implements Baseinterface{}
public interface Classinterface {}
And i want to use this code:
public class Myclass(Baseinterface interfaceversion) implements Classinterface{}
Where the kind of interface implementation is passed as a constructor.
So when a function is defined in both of those abstract classes my actual class knows which one to use. I am fairly new at java.
Thanks.
I may be misunderstanding the nature of the question, but here goes:
Given this code which describes two abstract classes that implement the same method as defined by an interface:
interface BaseInterface {
void foo();
}
abstract class ITestA implements BaseInterface {
public void foo() {
System.out.print("A");
}
}
abstract class ITestB implements BaseInterface {
public void foo() {
System.out.print("B");
}
}
public class MyClass {
private BaseInterface enclosed;
MyClass(BaseInterface base) {
enclosed = base;
}
public void foo() {
enclosed.foo(); // call the implementation specific to the instance passed in by constructor
}
}
This could be called like:
public class Test {
void bar() {
// This may look weird cause we're defining an anonymous implementation of the abstract class, without adding any new implementation details
ITestA impl = new ITestA() {};
MyClass myClass = new MyClass(impl);
myClass.foo(); // prints "A"
}
}
I have these 2 classes
class A {
public void foo1() {
...;
foo2();
...;
}
protected abstract foo2();
}
class B extends A {
public foo2() {
......
}
I need foo2 to be static so I can do B.foo2() but I also want the functionality in class A to remain.n
Any suggestions?
}
You can't override static methods or implement abstract methods as static.
Static methods are defined on a class definition, not on a class instance. Abstract methods are defined on a class instance.
What you said doesn't make sense in fact.
Although I don't quite get why you need to do it, there is a workaround:
class B {
#Override
public void foo() {
fooUtil();
}
public static void fooUtil() {
// your impl here
}
}
Then you can do B.fooUtil() instead, and using its behavior to override A.foo().
Assume I have defined interface ISomeInterface with methods foo and bar.
E.g.
public interface ISomeInterface {
public void foo();
public void bar();
}
Let's say I have classes A and B that for them it makes sense to both implement the interface. But it also does not make sense to have a different implementation for foo().
Taking into account that deriving A from B or B from A is incorrect/weird is there a standard coding practice for this design?
I assume I could create some utilities class to implement foo() and call it as a delegate but I was wondering if this whole structure can be dealt with differently
Update:
To give a full understanding of my question I stumbled upon this:http://perlbuzz.com/2010/07/why-roles-in-perl-are-awesome.html and I was trying to understand if this feature is lacking from the traditional OO concepts as we use them in Java or not
Your edit suggests that your true question is: "Is there an equivalent for Perl roles in Java?"
Since Java 8 introduced default methods in interfaces, interfaces with default methods seem like a very good equivalent for roles. Especially, you can do what you want in your example: Provide a default implementation for foo():
interface ISomeInterface {
public default void foo(){ /* your default impl goes here */}
public void bar(); // Abstract, must be implemented by subclasses
}
class A implements ISomeInterface {
// must only implement bar, can reuse foo's default impl
}
class B implements ISomeInterface {
// must only implement bar, can reuse foo's default impl
}
If there is a feature about roles I am missing please let me know. Otherwise, I think Java8 interfaces are a quite good surrogate for roles.
Decided to turn my comment into an answer:
You could use an abstract class rather than an interface:
public abstract class FooBar {
public void foo(){
//your implementation goes here
}
abstract void bar();
}
public class A extends FooBar{
#Override
public void bar(){
}
}
Why not something like this :
public class abstract SomeAbstractClass {
public void foo(){
//implementation
}
public abstract void bar();
}
class A extends SomeAbstractClass {
}
class B extends SomeAbstractClass {
}
public abstract class SomeClass implements ISomeInterface {
public void foo() {
// I do stuff..
}
}
public class A extends SomeClass {
public void bar() {
// A specific impl. of bar..
}
}
public class B extends SomeClass {
public void bar() {
// B specific impl. of bar..
}
}
Alternatively, if you don't want A and B to be tied up by extending an abstract class you can just use composition. This also provides the flexibility to change the IFoo behaviour at run time if you were to inject the FooImpl as part of the constructor. In this example I have just hard wired the FooImpl for brevity.
public class B implements ISomeInterface {
private IFoo foo = new FooImpl();
public void foo() {
foo.doSomethingFooey();
}
public void bar() {
// B specific implementation
}
}
public class A implements ISomeInterface {
private IFoo foo = new FooImpl();
public void foo() {
foo.doSomethingFooey();
}
public void bar() {
// A specific implementation
}
}
I am doing an exercise, the book is not helping me grasp the concept, neither are the online resources. This may seem really silly but I don't know what I'm missing!!! I am quite new to Java and have had a look at other examples on stack but to no avail :s I need to declare 3 interfaces. Each interface needs to declare a method with the same name as its interface. Then the abstract class is extended by 3 classes which implement the aforementioned interfaces.Each class needs to be instantiated. If anyone could explain the procedure to this I would be eternally grateful.
interface antiLockBrakes{
public void antiLockBrakes();
}
interface cruiseControl{
public void cruiseControl();
}
interface powerSteering{
public void powerSteering();
}
public abstract class Auto{
abstract class Model1 extends Auto implements antiLockBrakes{
public abstract void antiLockBrakes();
Model1 mod1 = new Model1();
mod1.antiLockBrakes();
}
public static void main(String[] args){
}
}
this is your question: someone to explain how exactly to declare and interface and then have it implemented in the abstract class right??
Here's the answer for it.
See lets consider I have an interface
interface someInterface{
public void someMethod();
}
Now to implement the someInterface in abstract class
public abstract class SomeClass implements someInterface{
public void someMethod(){
System.out.println("Inside someMethod");
}
public abstract myMethod();
}
See in the class SomeClass we have implemented interface by giving definition to method someMethod() and since we want this SomeClass to be a abstract class we have defined one abstract method myMethod() for it.
Now any class which extends from SomeClass will also implement interface someInterface implicitly (because SomeClass has implemented it) and if it want its own definition for someMethod() it can override it. But if a child class wants to be a concrete class ( a class in which all its method will have implementation) then it has to provide implementation for abstract method myMethod().
HTH:)
this is what I like to use to see the difference between abstract classes and interface classes
interface class
//I say all motor vehicles should look like that :
interface MotorVehicle {
void run();
int getFuel();
}
// my team mate complies and write vehicle looking that way
class Car implements MotorVehicle {
int fuel;
public void run() {
System.out.println("Wrroooooooom");
}
public int getFuel() {
return this.fuel;
}
}
abstract class
// I say all motor vehicles should look like that :
abstract class MotorVehicle2 {
int fuel;
// they ALL have fuel, so why let others implement that ?
// let's make it for everybody
int getFuel() {
return this.fuel;
}
// that can be very different, force them to provide their
// implementation
abstract void run();
}
// my team mate complies and write vehicle looking that way
class Car2 extends MotorVehicle2 {
void run() {
System.out.println("Wrroooooooom");
}
}
For a interface such as
public interface something<T>
{
public something<T> somemethod();
}
from what i understand the abstract method somemethod() needs to overridden with a method that returns an object implementing the interface. However, any attempts to do so have given me the "does not override the abstract method somemethod()" compiler error.
I've tried doing something like
public class someclass {
...
public something<T> somemethod() { ... return new someclass(); }
...
or
public someclass somemethod() { ... return new someclass(); }
...
}
How exactly would i implement such a method?
You're missing the generic declaration in your implementing class. Here's an example:
public interface Something <T> {
public Something<T> someMethod();
}
class SomethingImplementation <T> implements Something <T> {
#Override
public Something<T> someMethod() {
return null;
}
}
All of these should compile:
class test<T> implements something<T>{
public something<T> somemethod(){
return new test<T>();
}
}
class test1<T> implements something<T>{
public test1<T> somemethod(){
return new test1<T>();
}
}
class test2 implements something<Integer>{
public something<Integer> somemethod(){
return new test2();
}
}
class test3 implements something<Integer>{
public test3 somemethod(){
return new test3();
}
}
First of all, your someclass does not implement the interface in your code example above. You can make it implement the interface for a specific, concrete type, as in the following example, where String is used as the concrete type. The method then would need to return a something<String>.
public class someclass implements something<String> {
public something<String> somemethod() {
return new someclass();
}
}
Or you could have class someclass have a type parameter and use that for the interface:
public class someclass<X> implements something<X> {
public something<X> somemethod() {
return new someclass<X>();
}
}
from what i understand the abstract method somemethod() needs to
overridden with a method that returns an object implementing the
interface.
That is not correct. The method somemethod needs to return a something<T>.
You also need to extend the interface with a generic, such as:
public class someclass implements something {
public something somemethod() {
...
}
}
To override a method you have to implement a method with the same types of paramenters and the same type of return value.
String something(){} will be overriden by String something(){}
but NOT with char[] something(){} or String something(int){}
As I understand, you need to implement interface something, You can do this in simple way:
public class someclass<T> implements something<T> {
public something<T> somemethod() { ... return new someclass(); }
}
public class someclass<T> extends something<T> {
public something<T> somemethod() { ... return new someclass<T>(); }}