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"
}
}
Related
At the moment I have an abstract class which implements an interface. All implementations extend the abstract class to make there own implementation of the interface methods.
The abstract class holds methods which are the same for each implementation f.e. an execute method. I don't want to include the same 'execute' test for each implementation class.
I can successfully test the execute method in the abstract class by creating a test class for one of the implementation classes. The problem is that there will be more classes extending this abstract class and I don't want to write the same execute test in each of those classes.
I would like to somehow test the execute method from the abstract class only once in a specific test class so I can test only the implementation logic of all the other classes.
You can create a test class for your abstract class, too. Although you can't instantiate the abstract class directly, you can still create a concrete implementation class within your test file, just for testing the abstract class, implementing the required methods. You can get an instance for testing e.g. using an anonymous class:
AbstractClassType x = new AbstractClassType() {
#Override
public void doSomething() {
// ...
}
};
public interface BlaInterface {
public String getData();
}
public abstract class AbstractBla implements BlaInterface {
// methot to test only once and not for each class extending this
public void execute() {
// do some stuff which is the same for each extending class
getData();
}
}
public class BlaBla extends AbstractBla {
public String getData() {
return "Blabla";
}
}
So F.E. the above classes I can test the execute() method by testing the BlaBla class. But there will be more classes extending the abstract class and I find it ugly to put the execute() test just random in one of those classes.
So I would like an abstract test for the execute and other test classes just for testing getData f.e.
You can also create a parameterized test class, which takes the instances with the expected result as input and performs the tests.
(However, if you have much verification logic that strongly differs between the different instances, the approach by #vlumi to create an abstract test class might work better, because you can move the verification logic into abstract methods.)
public class MyParameterizedTests {
#ParameterizedTest
#MethodSource("getTestData")
public void test(TestData data) {
assertEquals(data.expectedResult, data.instance.compute());
}
public static TestData[] getTestData() {
return new TestData[] { new TestData(new X(), "x"), new TestData(new Y(), "y") };
}
}
class TestData {
public MyInterface instance;
public String expectedResult;
public TestData(MyInterface instance, String expectedResult) {
this.instance = instance;
this.expectedResult = expectedResult;
}
}
interface MyInterface {
String compute();
}
class X implements MyInterface {
#Override
public String compute() {
return "x";
}
}
class Y implements MyInterface {
#Override
public String compute() {
return "y";
}
}
what is the difference between creating an Object of interface and implementing an interface
example :
public interface A{
public void testMethod();
}
on way is creating an object of interface
public class B{
A a = new A(){
#override
public void testMethod(){ //implemtation here }
};
}
other way is
public class B implements A
{
#override
public void testMethod(){}
}
You are wrong:
here you anonymously implement interface and you alrady have instance of annonymouse class
public class B{
A a = new A(){
#override
public void testMethod(){ //implemtation here }
};
}
Here you create named implementation, you only create class without instantiate it.
public class B implements A
{
#override
public void testMethod(){}
}
You can't create an object of interface. Interface it's an abstract class but with all the methods are abstract. In the first code you are creating an anonymous class (i recommend you to read about this feature in java) that implements the interface A, in this case you are limited with the interface's methods even if you define additional method in your implementation you can't call it. In the second code you are creating a class that implements the interface A which means that you have a class that at least contain all the methods defined in the interface A and you can add inside your class B other methods and call its.
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
}
}
Java allows to assign subclass instances to class-typed fields, for example:
public class BaseClass {
}
public class SubClass extends BaseClass {
}
public class Example {
private BaseClass field1;
public void assign(SubClass subclass) {
field1 = subclass; // is OK
}
}
Java allows also to use interfaces as types. If we have an interface Fooable,
public interface Fooable {
void foo();
}
our Example class can have a field of type Fooable,
Fooable field2;
That is, it is possible to assign to field2 an instance of any class implementing Fooable interface.
But what if I want to tell the compiler that field3 has to be both an instance of BaseClass and implementation of Fooable interface? So that, if there is a class
public class FooSubClass extends BaseClass implements Fooable {
#Override
public void foo() {
// TODO
}
}
, I could assign to field3 instances of FooSubClass but not of SubClass?
Is it possible without using generics of any sort?
You can't do it like you are trying to.
You would need to define another class, perhaps an abstract class would suit you here:
public class abstract AbstractSubClass extends BaseClass implements Fooable {
...
}
Then FooSubClass:
public class FooSubClass extends AbstractSubClass {
...
}
Then your field is:
private AbstractSubClass field1;
Which will accept FooSubClass but not SubClass
Its the only way the compiler can guarantee that field1 will actually have implementations of all the required methods.
Here is a textbook example to illustrate:
public class Bird() {
public void eat() {
....
}
}
public interface FlyingBehaviour() {
void fly();
}
public abstract class FlyingBird extends Bird implements FlyingBehaviour() {
...
}
public class Eagle extends FlyingBird {
...
}
public class Penguin extends Bird {
...
}
FlyingBird bird = new Eagle();
bird.fly();
FlyingBird bird = new Penguin(); //Compilation Error - Penguins cant fly!
There is no way in java to ensure a object field inherits/implements two different classes.
Assuming you have control of all the objects here, the easiest fix would be for your base class to implement Fooable.
Since you are using a assign-method for setting the fields, you can check if it is correct type of object using instanceof in that method.
public void assign(BaseClass baseClass) {
if (baseClass instanceof foo)
field3 = baseClass;
}
You may throw an exception if class not implementing foo is provided.
edit:
Doh, didn't see that the fix should be for compile-time.