Related
I have two interfaces Inquiry and Validatable
and I also have two classes ErrorReport and FunctionQuery implements Inquiry and Validatable both.
What is the best choice when I have a logic that uses a combination of two interfaces' operation?
I know that I can separate it into two logic using Inquiry and Validatable, but the logic is combined so If I separate it, it makes other duplication.
I tried like below, but, I realized this hierarchy is not appropriate because Validatable is not a generalization of Inquiry in my application.
approach at first
public interface Inquiry extends Validatable {
...
}
and classes like this.
public class ErrorReport implements Inquiry{
...
}
public class FunctionQuery implements Inquiry {
...
}
new approach
So I create an interface like below.
public interface ValidatableInquiry extends Inquiry,Validatable{
...
}
and classes
public class ErrorReport implements ValidatableInquiry {
...
}
public class FunctionQuery implements ValidatableInquiry {
...
}
I think the new approach is better than the first, but I can't be assured.
Is it the right approach? and Is there a better alternative?
To a certain degree, this is opinionated. Both solutions "work" for a smaller project of limited life time.
But then it is very clear that the first solution carries one significant constraint: it introduces coupling between Inquiry and Validatable.
Thus the answer is: if you are really sure about your "model", and the abstractions that you want to create ... in the sense of: yes, absolutely, any Inquiry will always be a Validatable, too, then that solution is okay. Because your code matches your mental model, and you are sure about the validity of your mental model.
But if there is the slightest doubt that these two interface are actually independent of each other, then you should pick the 2nd approach. Because that approach says: the two interfaces are independent, and classes that need both functionalities can extend from that joining interface that brings the functionalities together.
I'm porting some Python code to Java, and I am having trouble dealing with the following problem:
I have some classes which need to have abilities A, B, or C. Class 1 needs ability A, class 2 needs A, B and C, and class 3 needs B and C. Most importantly, I want to easily be able to change what class can have what ability in the future.
I solved this problem pretty easily with multiple inheritance in Python. I'm trying to figure out the best way to do it in Java, but I can't come up with as good of a solution. I know multiple inheritance is frowned-upon, so I'd appreciate being taught a better way.
Thanks!
It depends on your actual use case, but have you already considered decorators?
http://en.wikipedia.org/wiki/Decorator_pattern
Multiple-inheritance ain't frowned upon. What is frowned upon is "implementation inheritance" (also known as "code reuse"), because it leads to the unsolvable "diamond problem". And because, well, code-reuse really hasn't much to do with OO.
What you want to do can be solved using multiple inheritance (and, say, delegation if you need to do "code reuse").
interface A {
void move();
}
interface B {
void eat();
}
interface C {
void think();
}
class One implements A { ... }
class Two implements B { ... }
class Three implements B, C { ... }
Any OOA/OOD using multiple inheritance can be trivially translated to Java. The part where you say that you need to change the "ability" all the time is a bit scary: if, say, a Car can move(), why would it suddenly need to be able to think()?
You can use AspectJ's mixin syntax fairly easily to emulate multiple inheritance (and at compile time too). First, declare an interface for the functionality you want to mixin:
public interface A{
String getSomethingForA();
}
then define an annotation which you can use to signify that you want the mixin applied to a given class:
public #interface WithA {}
then add the annotation to the class you want to use:
#WithA
public class MyClass {}
then, to actually add some functionality:
#Aspect
public class MixinA {
public static class AImpl implements A{
public String getSomethingForA() {
return "it worked!";
}
}
#DeclareMixin("#WithA *")
public static A get() {
return new AImpl();
}
}
You'll need to use the aspectj jars and run the aspects as part of your compile process, but this lets you create truly modularized functionality and then forcibly merge it into your classes later. To access your class with the new functionality, do the following:
MyClass obj = new MyClass();
((A)obj).getSomethingForA();
You can apply the same annotation to another class and cast it as well:
#WithA
#WithB //let's pretend we created this with some other functionality
public class AnotherClass {}
AnotherClass anotherObj = new AnotherClass();
((A)anotherObj).getSomethingForA();
((B)anotherObj).andSetSomethingElseForB("something else");
Multiple inheritance is almost always a bad idea, as its effects can usually be achieved through other mechanisms. Based upon your description of the problem, it sounds like you want to
Use interfaces to define behavior (public interface A) in this scenario, each behavior should probably have its own interface.
If 2 behaviors are tightly coupled (say A & B), define an interface that implements those two atomic interfaces (public interface CombinedAandB extends A, B)
Define an abstract base class that implements the interface to provide default implementations for behaviors
public abstract class BaseAB implements A, B
{
#Override
public void A() { add(0,1); }
#Override
public void B() {add(1,0); }
private void add(int a, int b) //it doesn't return. no soup for you.
{ a + b; //If you know why this is wrong, high five yourself. }
}
Define a concrete class that extends the abstract base class, implements another interface, and provides its own behavior.
public class IDoABAndC extends BaseAB implements C
{
//stuff, etc
}
You can define the abilities in interfaces and implement them in your classes.
In java you don't have multiple inheritance, instead you can implement multiple interfaces.
So your class 1 will implement interface A and B. Class 2 will implement interface A, B and C. Class 3 will implement B and C.
If what you need is interface inheritance, then as mentioned before, you can always implement multiple interfaces.
If you're looking for implementation inheritance, you're somewhat out of luck. The best solution is probably to use delegation — replace the extra superclasses with fields, and implement methods that just delegate to those fields. It does require writing a lot of repetitive delegation methods, but it's rather unavoidable in Java (without resorting to AspectJ or other bytecode-munging tricks; careful, this way madness lies …).
This is a bit tangential, but you can have python code running in Java via Jython (http://www.jython.org/). This addresses the porting to Java part, not the solving multiple inheritance part (I think you need to determine which is relevant)
I am reading "The Java Tutorial" (for the 2nd time). I just got through the section on Interfaces (again), but still do not understand how Java Interfaces simulate multiple inheritance. Is there a clearer explanation than what is in the book?
Suppose you have 2 kinds of things in your domain : Trucks and Kitchens
Trucks have a driveTo() method and Kitchens a cook() method.
Now suppose Pauli decides to sell pizzas from the back of a delivery truck. He wants a thing where he can driveTo() and cook() with.
In C++ he would use multiple inheritance to do this.
In Java that was considered to be too dangerous so you can inherit from a main class, but you can "inherit" behaviors from interfaces, which are for all intents and purposes abstract classes with no fields or method implementations.
So in Java we tend to implement multiple inheritance using delegations :
Pauli subclasses a truck and adds a kitchen to the truck in a member variable called kitchen. He implements the Kitchen interface by calling kitchen.cook().
class PizzaTruck extends Truck implements Kitchen {
Kitchen kitchen;
public void cook(Food foodItem) {
kitchen.cook(foodItem);
}
}
He is a happy man because he can now do things like ;
pizzaTruck.driveTo(beach);
pizzaTruck.cook(pizzaWithExtraAnchovies);
Ok, this silly story was to make the point that it is no simulation of multiple inheritance, it is real multiple inheritance with the proviso that you can only inherit the contract, only inherit from empty abstract base classes which are called interfaces.
(update: with the coming of default methods interfaces now can also provide some behavior to be inherited)
You're probably confused because you view multiple inheritance locally, in terms of one class inheriting implementation details from multiple parents. This is not possible in Java (and often leads to abuse in languages where it's possible).
Interfaces allow multiple inheritance of types, e.g. a class Waterfowl extends Bird implements Swimmer can be used by other classes as if it were a Bird and as if it were a Swimmer. This is the the deeper meaning of multiple inheritance: allowing one object to act like it belongs to several unrelated different classes at once.
Here is a way to achieve multiple inheritance through interfaces in java.
What to achieve?
class A extends B, C // this is not possible in java directly but can be achieved indirectly.
class B{
public void getValueB(){}
}
class C{
public void getValueC(){}
}
interface cInterface{
public getValueC();
}
class cChild extends C implemets cInterface{
public getValueC(){
// implementation goes here, call the super class's getValueC();
}
}
// Below code is **like** class A extends B, C
class A extends B implements cInterface{
cInterface child = new cChild();
child.getValueC();
}
given the two interfaces below...
interface I1 {
abstract void test(int i);
}
interface I2 {
abstract void test(String s);
}
We can implement both of these using the code below...
public class MultInterfaces implements I1, I2 {
public void test(int i) {
System.out.println("In MultInterfaces.I1.test");
}
public void test(String s) {
System.out.println("In MultInterfaces.I2.test");
}
public static void main(String[] a) {
MultInterfaces t = new MultInterfaces();
t.test(42);
t.test("Hello");
}
}
We CANNOT extend two objects, but we can implement two interfaces.
Interfaces don't simulate multiple inheritance. Java creators considered multiple inheritance wrong, so there is no such thing in Java.
If you want to combine the functionality of two classes into one - use object composition. I.e.
public class Main {
private Component1 component1 = new Component1();
private Component2 component2 = new Component2();
}
And if you want to expose certain methods, define them and let them delegate the call to the corresponding controller.
Here interfaces may come handy - if Component1 implements interface Interface1 and Component2 implements Interface2, you can define
class Main implements Interface1, Interface2
So that you can use objects interchangeably where the context allows it.
It's pretty simple. You can implement more than one interface in a type. So for example, you could have an implementation of List that is also an instance of Deque (and Java does...LinkedList).
You just can't inherit implementations from multiple parents (i.e. extend multiple classes). Declarations (method signatures) are no problem.
You know what, coming from the perspective of a JavaScript dev trying to understand what the heck is going on with this stuff, I'd like to point out a couple things and somebody please tell me what I'm missing here if I'm way off the mark.
Interfaces are really simple. Stupidly, insanely simple. They're as stupidly, insanely simple as people initially think, which is why there are so many duplicate questions on this exact subject because the one reason to use them has been made unclear by people trying to make more of them than they are and there is widespread misuse in every Java server-side code-base I've ever been exposed to.
So, why would you want to use them? Most of the time you wouldn't. You certainly wouldn't want to use them ALL the time as many seem to think. But before I get to when you would, let's talk about what they're NOT.
Interfaces are NOT:
in any way a workaround for any sort of inheritance mechanism that Java lacks. They have nothing to do with inheritance, they never did, and in no way simulate anything inheritance-like.
necessarily something that helps you with stuff you wrote, so much as it helps the other guy write something meant to be interfaced by your stuff.
They really are as simple as you think they are on first glance. People misuse stupidly all the time so it's hard to understand what the point is. It's just validation/testing. Once you've written something conforms to an interface and works, removing that "implements" code won't break anything.
But if you're using interfaces correctly, you wouldn't want to remove it because having it there gives the next developer a tool for writing an access layer for another set of databases or web services that they want the rest of your app to continue using because they know their class will fail until they get the 100% complete-as-expected-interface in place. All interfaces do is validate your class and establish that you have in fact implemented an interface as you promised you would. Nothing more.
They're also portable. By exposing your interface definitions you can give people wanting to use your unexposed code a set of methods to conform to in order for their objects to use it correctly. They don't have to implement the interfaces. They could just jot them down on a piece of notepad paper and double-check that. But with the interface you have more of a guarantee nothing is going to try to work until it has a proper version of the interface in question.
So, any interface not likely to ever be implemented more than once? Completely useless. Multiple-inheritance? Stop reaching for that rainbow. Java avoids them for a reason in the first place and composited/aggregate objects are more flexible in a lot of ways anyway. That's not to say interfaces can't help you model in ways that multiple-inheritance allows but it's really not inheritance in any way shape or form and shouldn't be seen as such. It's just guaranteeing that your code won't work until you've implemented all of the methods you established that you would.
It's not a simulation of multiple inheritance. In java you can't inherit from two classes, but if you implements two interfaces "it seems like you inherited from two different classes" because you can use your class as any of your two intefaces.
For example
interface MyFirstInteface{
void method1();
}
interface MySecondInteface{
void method2();
}
class MyClass implements MyFirstInteface, MySecondInteface{
public void method1(){
//Method 1
}
public void method2(){
//Method 2
}
public static void main(String... args){
MyFirstInterface mfi = new MyClass();
MySecondInterface msi = new MyClass();
}
}
This will work and you can use mfi and msi, it seems like a multi inheritance, but it's not because you don't inherit anything, you just rewrite public methods provided by the interfaces.
You need to be precise:
Java allows multiple inheritance of interface, but only single inheritance of implementation.
You do multiple inheritance of interface in Java like this:
public interface Foo
{
String getX();
}
public interface Bar
{
String getY();
}
public class MultipleInterfaces implements Foo, Bar
{
private Foo foo;
private Bar bar;
public MultipleInterfaces(Foo foo, Bar bar)
{
this.foo = foo;
this.bar = bar;
}
public String getX() { return this.foo.getX(); }
public String getY() { return this.bar.getY(); }
}
Just by the way, the reason why Java does not implement full multiple inheritance is because it creates ambiguities. Suppose you could say "A extends B, C", and then both B and C have a function "void f(int)". Which implementation does A inherit? With Java's approach, you can implement any number of interfaces, but interfaces only declare a signature. So if two interfaces include functions with the same signature, fine, your class must implement a function with that signature. If interfaces you inherit have functions with different signatures, then the functions have nothing to do with each other, so there is no question of a conflict.
I'm not saying this is the only way. C++ implements true multiple inheritance by establishing precedence rules of which implementation wins. But the authors of Java decided to eliminate the ambiguity. Whether because of a philosophical belief that this made for cleaner code, or because they didn't want to do all the extra work, I don't know.
It's not fair to say that interfaces 'simulate' multiple inheritance.
Sure, your type can implement multiple interfaces and act as many different types polymorphically. However, you obviously won't inherit behaviour or implementations under this arrangement.
Generally look at composition where you think you may need multiple inheritance.
OR A potential solution to achieving something multiple inheritance like is the Mixin interface - http://csis.pace.edu/~bergin/patterns/multipleinheritance.html. Use with care!
They don't.
I think that the confusion comes from people believing that implementing an interface constitutes some form of inheritance. It doesn't; the implementation can simply be blank, no behavior is forced by the act or guaranteed through any contract. A typical example is the Clonable-interface, which while alluding to lots of great functionality, which defines so little that's it's essentially useless and potentially dangerous.
What do you inherit by implementing an interface? Bubkes! So in my opinion, stop using the words interface and inheritance in the same sentence. As Michael Borgwardt said, an interface is not a definition but an aspect.
You can actually "inherit" from multiple concrete classes if they implement interfaces themselves. innerclasses help you achieve that:
interface IBird {
public void layEgg();
}
interface IMammal {
public void giveMilk();
}
class Bird implements IBird{
public void layEgg() {
System.out.println("Laying eggs...");
}
}
class Mammal implements IMammal {
public void giveMilk() {
System.out.println("Giving milk...");
}
}
class Platypus implements IMammal, IBird {
private class LayingEggAnimal extends Bird {}
private class GivingMilkAnimal extends Mammal {}
private LayingEggAnimal layingEggAnimal = new LayingEggAnimal();
private GivingMilkAnimal givingMilkAnimal = new GivingMilkAnimal();
#Override
public void layEgg() {
layingEggAnimal.layEgg();
}
#Override
public void giveMilk() {
givingMilkAnimal.giveMilk();
}
}
I'd like to point out something that bit me in the behind, coming from C++ where you can easily inherit many implementations too.
Having a "wide" interface with many methods means that you'll have to implement a lot of methods in your concrete classes and you can't share these easily across implementations.
For instance:
interface Herbivore {
void munch(Vegetable v);
};
interface Carnivore {
void devour(Prey p);
}
interface AllEater : public Herbivore, Carnivore { };
class Fox implements AllEater {
...
};
class Bear implements AllEater {
...
};
In this example, Fox and Bear cannot share a common base implementation for both it's interface methods munch and devour.
If the base implementations look like this, we'd maybe want to use them for Fox and Bear:
class ForestHerbivore implements Herbivore
void munch(Vegetable v) { ... }
};
class ForestCarnivore implements Carnivore
void devour(Prey p) { ... }
};
But we can't inherit both of these. The base implementations need to be member variables in the class and methods defined can forward to that. I.e:
class Fox implements AllEater {
private ForestHerbivore m_herbivore;
private ForestCarnivore m_carnivore;
void munch(Vegetable v) { m_herbivore.munch(v); }
void devour(Prey p) { m_carnivore.devour(p); }
}
This gets unwieldy if interfaces grow (i.e. more than 5-10 methods...)
A better approach is to define an interface as an aggregation of interfaces:
interface AllEater {
Herbivore asHerbivore();
Carnivore asCarnivore();
}
This means that Fox and Bear only has to implement these two methods, and the interfaces and base classes can grow independetly of the aggregate AllEater interface that concerns the implementing classes.
Less coupling this way, if it works for your app.
I don't think they do.
Inheritance is specifically an implementation-oriented relationship between implementations. Interfaces do not provide any implementation information at all, but instead define a type. To have inheritance, you need to specifically inherit some behaviors or attributes from a parent class.
I believe there is a question here somewhere specifically about the role of interfaces and multiple inheritance, but I can't find it now...
There's really no simulation of multiple inheritance in Java.
People will sometimes say that you can simulate multiple inheritance using Interfaces because you can implement more than one interface per class, and then use composition (rather than inheritance) in your class to achieve the behaviors of the multiple classes that you were trying to inherit from to begin with.
If it makes sense in your object model, you can of course inherit from one class and implement 1 or more interfaces as well.
There are cases where multiple-inheritance turns to be very handy and difficult to replace with interfaces without writing more code. For example, there are Android apps that use classes derived from Activity and others from FragmentActivity in the same app. If you have a particular feature you want to share in a common class, in Java you will have to duplicate code instead of let child classes of Activity and FragmentsActivity derive from the same SharedFeature class. And the poor implementation of generics in Java doesn't help either because writing the following is illegal:
public class SharedFeature<T> extends <T extends Activity>
...
...
There is no support for multiple inheritance in java.
This story of supporting multiple inheritance using interface is what we developers cooked up. Interface gives flexibility than concrete classes and we have option to implement multiple interface using single class. This is by agreement we are adhering to two blueprints to create a class.
This is trying to get closer to multiple inheritance. What we do is implement multiple interface, here we are not extending (inheriting) anything. The implementing class is the one that is going to add the properties and behavior. It is not getting the implementation free from the parent classes. I would simply say, there is no support for multiple inheritance in java.
No, Java does not support multiple inheritance.
Neither using class nor using interface. Refer to this link for more info
https://devsuyed.wordpress.com/2016/07/21/does-java-support-multiple-inheritance
I also have to say that Java doesn't support multiple inheritance.
You have to differentiate the meaning between extends and implements keywords in Java. If we use extends, we are actually inheriting the class after that keyword. But, in order to make everything simple, we can't use extends more than once. But you can implement as many Interfaces as you wish.
If you implement an interface, there's a zero chance that you will miss the implementation of all the methods in each interface (Exception: default implementations of interface methods introduced in Java 8) So, you are now fully aware of what is happening with the things that you have embedded to your fresh class.
Why Java doesn't allow multiple inheritance is actually, multiple inheritance makes the code somewhat complex. Sometimes, two methods of parent classes might conflict due to having the same signatures. But if you are forced to implement all the methods manually, you will get the full understanding about what's going on, as I mentioned above. It makes your code more understandable to you.
If you need more info on Java interfaces, check out this article, http://www.geek-programmer.com/introduction-to-java-interfaces/
Between two Java class multiple Inheritance directly is not possible. In this case java recommend Use to interface and declare method inside interface and implement method with Child class.
interface ParentOne{
public String parentOneFunction();
}
interface ParentTwo{
public String parentTwoFunction();
}
class Child implements ParentOne,ParentTwo{
#Override
public String parentOneFunction() {
return "Parent One Finction";
}
#Override
public String parentTwoFunction() {
return "Parent Two Function";
}
public String childFunction(){
return "Child Function";
}
}
public class MultipleInheritanceClass {
public static void main(String[] args) {
Child ch = new Child();
System.out.println(ch.parentOneFunction());
System.out.println(ch.parentTwoFunction());
System.out.println(ch.childFunction());
}
}
For my semester project, my team and I are supposed to make a .jar file (library, not runnable) that contains a game development framework and demonstrate the concepts of OOP. Its supposed to be a FRAMEWORK and another team is supposed to use our framework and vice-versa. So I want to know how we should start. We thought of several approaches:
1. Start with a plain class
public class Enemy {
public Enemy(int x, int y, int health, int attack, ...) {
...
}
...
}
public class UserDefinedClass extends Enemy {
...
}
2. Start with an abstract class that user-defined enemies have to inherit abstract members
public abstract class Enemy {
public Enemy(int x, int y, int health, int attack, ...) {
...
}
public abstract void draw();
public abstract void destroy();
...
}
public class UserDefinedClass extends Enemy {
...
public void draw() {
...
}
public void destroy() {
...
}
}
3. Create a super ABC (Abstract Base Class) that ALL inherit from
public abstract class VectorEntity {
...
}
public abstract class Enemy extends VectorEntity {
...
}
public class Player extends VectorEntity {
...
}
public class UserDefinedClass extends Enemy {
...
}
Which should I use? Or is there a better way?
Well, it's a bit hard to say for sure without knowing in depth what you're doing, and even then it's rather subjective. However, there are some things to consider which could tell you.
Are they going to actually instantiate an Enemy, or do all enemies really need to be of a derived type? If you're not actually going to be instantiating Enemies rather than derived types, then it should likely be either an interface or an abstract class.
If you're looking to provide actual behavior in your base class, then obviously it needs to be a class rather than an interface.
Methods which need to be there for the API but don't make any sense for you to be providing any implementations for should be abstract.
Methods where it makes good sense to have implementations for them in the base class should have implementations in the base class. And if it doesn't make good sense for them to be overridden, then make them final.
Making classes share a common base class really only makes sense if they're really sharing behavior or you need to be able to treat them all the same somewhere in your code. If they're not really all that similar, then they probably shouldn't share a base class. For instance, if both Enemy and Player are supposed to be displayable, it may make sense to have a common base class which handles their display functionality. But if Enemy were something that was displayable, and Player was a more abstract concept - like the controller of the game - and wasn't displayable, then it probably wouldn't make sense for them to share a base class. In general, it's better to prefer composition rather than inheritance when building classes, so if the classes in question aren't really going to be sharing behavior and don't really have an "is-a" relationship with a common base class, then they shouldn't share a common base class.
Prefer to have your base classes only share methods, not data. In other words, in an inheritance tree, it's best that only the leaves be instantiable. There are various things like equals() which break down when you have base classes with actual data in them. That's not to say that you can't do that - people do it all the time - but it can cause problems and is best avoided if it isn't needed.
Prefer to override abstract methods. Otherwise, in derived classes, you risk not calling the base class' method or totally changing what the method does.
I'm sure that I could come up with more, but without really being familiar with your project, it's bound to be rather generic. Out of the 3 options that you gave, I'd probably go with 2. 3 seems like you'd probably be creating a base class for unrelated classes, and 1 would result in Enemy being instantiatable, which you probably don't need and would definitely make it so that more than the leaves in your inheritance hierarchy would be instantiatable. You'll probably still end up with data in base classes with 2, but you're more likely to only be overriding abstract methods, and you'll have fewer problems with altered behavior in derived classes.
A fourth option would be to use interfaces.
interface Enemy {
public void draw();
. . .
}
If you're just starting out, I would avoid your third option. Let the framework develop a little and see if there's a need for it.
My rule of conduct is that a long as there are more than one class that share the same operations/data/methods/functionality, they should be extensions of the same abstract class.
So, if it was me doing it:
If ALL classes have something in common, have an top-level abstract class that gathers this functionality/fields/data in one place.
If they don't, only those classes that actually have something in common should extend a lower-level abstract class.
If only methods are what the classes will have in common, interfaces can be used as well. However, I always find that sooner or later I see that the classes that implement the interface have the same private fields. At this point, I transform the interface to an abstract class that holds these private fields (to save on lines of code if nothing else).
Just a small answer out of the book "More effective c++" page 271:
"Make base classes abstract that are not at the end of a hierachy". I'm too lazy to give you the whole chapert, but the autor lists some good reasons for that.
Before asking question, let me explain the current setup:
I have an service interface, say Service, and one implementation, say ServiceImpl. This ServiceImpl uses some other services. All the services are loaded as bean by spring.
Now, I want to write junit test cases for the ServiceImpl. For the same, I use the applicationContext to get the Service bean and then call different methods on it to test them.
All looks fine for the public methods but how do I write test cases for private methods? Because we might not have the same private methods for different implementations?
Can anyone help me here on what should be preferred way of writing test cases?
The purist answer is that private methods are called that for a reason! ;-)
Turn the question around: given only the specification of a (publicly-accessible) interface, how would you lay out your test plan before writing the code? That interface describes the expected behavior of an object that implements it; if it isn't testable at that level, then there's something wrong with the design.
For example, if we're a transportation company, we might have these (pseudo-coded) interfaces:
CapitalAsset {
Money getPurchaseCost();
Money getCurrentValue();
Date whenPurchased();
...
}
PeopleMover {
Weight getVehicleWeight();
int getPersonCapacitly();
int getMilesOnFullTank();
Money getCostPerPersonMileFullyLoaded(Money fuelPerGallon);
...
}
and might have classes including these:
Bus implements CapitalAsset, PeopleMover {
Account getCurrentAdvertiser() {...}
boolean getArticulated() {...}
...
}
Computer implements CapitalAsset {
boolean isRacked() {...}
...
}
Van implements CapitalAsset, PeopleMover {
boolean getWheelchairEnabled() {...}
...
}
When designing the CapitalAsset concept and interface, we should have come to agreement with the finance guys as to how any instance of CapitalAsset should behave. We would write tests against CapitalAsset that depend only on that agreement; we should be able to run those tests on Bus, Computer, and Van alike, without any dependence on which concrete class was involved. Likewise for PeopleMover.
If we need to test something about a Bus that is independent from the general contract for CapitalAsset and PeopleMover then we need separate bus tests.
If a specific concrete class has public methods that are so complex that TDD and/or BDD can't cleanly express their expected behavior, then, again, that's a clue that something is wrong. If there are private "helper" methods in a concrete class, they should be there for a specific reason; it should be possible to ask the question "If this helper had a defect, what public behavior would be affected (and how)?"
For legitimate, inherent complexity (i.e. which comes from the problem domain), it may be appropriate for a class to have private instances of helper classes which take on responsibility for specific concepts. In that case, the helper class should be testable on its own.
A good rule of thumb is:
If it's too complicated to test, it's too complicated!
Private methods should be exercised through the public interface of a class. If you have multiple implementations of the same interface, I'd write test classes for each implementation.
You have written multiple implementations of an interface and want to test all implementations with the same JUnit4-test. In the following you will see how you can do this.
Also there is an example that shows how to get a new instance for each test case.
Example Code
Before I start explaining things here’s some example code for the java.util.list interface:
public class ListTest {
private List<Integer> list;
public ListTest(List<Integer> list){
this.list = list;
}
#Parameters
public static Collection<Object[]> getParameters() {
return Arrays.asList(new Object[][] {
{ new ArrayList<Integer>() },
{ new LinkedList<Integer>()}
});
}
#Test
public void addTest(){
list.add(3);
assertEquals(1, list.size());
}
}
I think you should split the testcases.
First you test the class which is calling the different implementations of the interfaces. This would mean you are testing the public methodes.
After this you test the interface implementaion classes in another testcase. Their you can call the methode with reflection.
I found an interesting article on how to test private methods with JUNIT at http://www.artima.com/suiterunner/privateP.html
So, I assume we should prefer testing private methods indirectly by testing the public methods. Only in exceptional circumstances, we should think of testing private methods.