interface A {
void someMethod();
}
class B implements A {
void someMethod() {
//do something
}
}
class C extends B implements A {
void someMethod() {
super.someMethod();
//do something
}
}
I'm using the above design in one of my codes. It is working fine. My whole purpose here is to use the default implementation of class B and do something extra in class C. Is this the correct way to use the implementation? Is there any better design patter to be looked at?
Because If I define my class C as below, still everything works fine. But this neglects the whole purpose of using implementation (to force class C to implement methods of interface A).
class C extends B implements A {}
Yes, it's perfectly fine to both extend and implement on the same classes.
in fact, if you'll look at HashMap (and many others), that's exactly what it does:
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
It still works fine because when you extend B that comes along with an implementation of someMethod, thus fulfilling the contract.
Please understand that
class C extends B implements A is exactly equal to class C extends B other than the quick documentation purpose.
Try removing the defination of someMethod() from class C and see if your code compiles or not. It will compile. The reason is, the moment you made C extend B, C by default gets all the methods defined in B which includes an impementation of someMethod() as well. Defying the whole purpose of your explicit contract.
If you really want to force C to give a defination of someMethod() then try the following code:
interface A {
void someMethod();
}
abstract class B implements A {
protected void someUtilMethod() {
//do common/default defination
}
}
class C extends B {
void someMethod() {
someUtilMethod();
//do extra something
}
}
Related
Suppose I have an interface defined as:
public interface TestInterface1 {
public void add();
}
which is implemented by classes A, B and C.
Now I need to add a subtract functionality only to class C; for that I have created a new interface TestInterface2 and implemented that to class C:
public interface TestInterface2 {
public void sub();
}
Class C looks like this:
public class C implements TestInterface1, TestInterface2 {
public void add() {
System.out.println("I am in add");
}
public void sub() {
System.out.println("I am in Sub");
}
}
Now the problem is instances of C has been use in hundreds of places like this:
TestInterface1 c = new C();
And only class C is getting the add method of TestInterface1.
Is there any way or pattern to implement both the interfaces in class C so that where ever the object of class C is created, it gets both the method from TestInterface1 and TestInterface2?
If you can change your interfaces then make TestInterface1 extend the other one, so object created using first interface can use its parent methods.
public interface TestInterface1 extends TestInterface2{
public void add();
}
Before we get into this, you have to consider why you're even using interfaces for this at all. An interface guarantees that all instances are using the same implementations. If you want a specific class to have a more specific implementation, then that sounds more like a method on the concrete class more than it does a new interface at all.
Regardless, we can discuss your options. One of them is cleaner and conveys clear intent; the other muddies things.
The first option - which conveys clearer intent - is to eschew the usage of the more restrictive interface and instead use TestInterface2 for every declaration that you want to use C.
This means you'd write TestInterface2 c = new C(); everywhere you wanted to use it. Yes, you'd be changing it in all of the places that you're using C, but given that you have to have a method specifically attached to instances of C, this option is clearest.
This would be the same approach if you just wrote the method in C. There's really no difference between the two and I personally would prefer if you wrote the method that only belonged to C in C.
The second option - which muddies things and also requires Java 8 - is to use a default method. This requires that you implement it in the interface at first...
public interface TestInterface {
default void sub() {
System.out.println("I am in sub!");
}
}
...but you can override it in your class later. This muddies things because any class that implements TestInterface has access to this default method, which is likely not what you want for your requirements.
I have
public abstract class A
{
public abstract A get();
}
and
public abstract class B
{
public abstract void save(A a);
}
And bunch of different classes that extend these two classes.
And they are usually paired together. So if I have classes C, D
Then C would extend A and D would extend B and D's save function would expect C in order for it to work.
And I have controller E
public class E
{
List<B> list;
public void save(A a)
{
// how do I choose correct pair from list?
}
}
In that controller I have a list of classes that extend B.
There is a save function in E that receives extended class A as an argument.
How do I loop through all the elements in the list and figure out which class belongs to which in the pair?
Thanks to anyone for their help, I am trying to learn complex abstract classes and how to relate them.
EDIT: If I use instance of then I will have a huge if statements inside 100 classes
Let's say I have 100 classes that extend class A and 100 that extend class B.
They are paired together as I explained above.
So as a further clarification.
public class D extends B
{
public void save(A a)
{
C c = (C)a.get();
// proceed saving using c
}
}
How do I avoid doing a check for instance of inside all these classes, and know how to pair them? Is there no better way?
EDIT2: Pshemo answer is great, however I have one last question to solve.
In class E I have save function that receives class A
How do I know which class that A is linked to?
If class A is instance of C how would I know to search for instance of D in the list and call that classes' save function?
I am not sure if that is what you need, but it looks like you may want to change B class to something like
abstract class B<T extends A> {
public abstract void save(T a);
}
so now when you extend it you can specify which class should T represent, like
class D extends B<C> {
public void save(C a) {}
}
I'm new to Java but used to OOP programming. Is there a way I can force implementing an abstract class nested into another abstract class like in the code below :
public abstract class A
{
public abstract class B extends C
{
#Override
public abstract void foo();
}
}
I would like B to be implemented in each subclass of A. Is it possible?
Thank you for your help,
If I read your question correctly, where you want each sub-class of A to CONTAIN a subclass of B, there is not a direct way to do this. However, you could do something like the below:
public abstract class A
{
public abstract class B extends C
{
#Override
public abstract void foo();
}
protected abstract B getBInstance();
}
Because this forces sub-class of A to return an instance of B, they must have access to some sub-class of B.
However, you should really ask yourself why A should care about its sub-classes implementing B unless A uses B in some way which would require the above.
Yes, make B an interface, as shown in When an Abstract Class Implements an Interface.
This is not possible. The A class should only provide what behaviour an instance of A has (either through the abstract or implemented methods). It should not state anything about how A is implemented.
It's not even clear how this would be useful either since you could not call the implemented class B so it would need to be named something else meaning it's existence could be ignored.
Say that I in Java have 3 classes, wheres the super one has a function named func(), I now make a subclass which overrides this, and a subclass to my subclass, now working on my sub-sub-class how will I call the 'func()' of the sub class, and the superclass?
I tried casting the 'this' "pointer", but Java 'fixes' it at runtime and calls the subsub func().
Edit:
Thanks everyone; 'Skeen is back at the drawing board'.
The best you can do is call super.func() in your subsub class, and have the func() implementation in your subclass also call super.func().
However, ask yourself, if I need knowledge not only of my parents implementation but also my grandparents implementation, do I have a design problem? Quite frankly this is tripping my "Something stinks in the fridge" instinct. You need to re-evaluate why you want to do this.
This isn't possible in Java. And btw. there aren't any pointers in Java.
I would jump on the "something in this design smells funny" train. Normally, you override a method so that it works properly for that specific subclass. If you have code in your parent class that is shared across multiple subclasses, perhaps that code could be moved to a non-overridden method so that it is readily accessible by all children/granchildren/etc.
Could you perhaps flip your design over and use more of a template method approach? (http://en.wikipedia.org/wiki/Template_method_pattern)
The notion behind Template Method is that you have some algorithm in your parent class and you can fill in the pieces that need to be class specific by polymorphic calls into your subclasses. You don't have a ton of detail in your question, but by the sounds of things, I'd really take a good look at your design and see if it makes sense.
Why don't you have func() be not inherited (call it funcBase() or whatever) and then add a wrapper func() function that calls it?
class A{
public void funcBase() {
// Base implementation
}
public void func() {
funcBase();
}
}
class B extends A{
public void func(){
super.func();
}
}
class C extends B{
public void foo(){
super.func(); // Call B's func
funcBase(); // Call A's func
}
}
I have no idea what you're trying to do, but it sounds like your class design is not appropriate for what you want, so you may want separate functions in A instead of trying to sneak your way up the ladder.
This example is the only way to call a "grandparent" super method.
class A{
public void foo(){ System.out.println("Hi"); }
}
class B extends A{
public void foo(){ super(); }
}
class C extends B{
public void foo(){ super(); }
}
This would be a different story if B doesn't override foo().
Another option would be to have a "protected helper" method in the middle class.
class D{
public void foo(){ System.out.println("Hi"); }
}
class E extends D{
public void foo(){ System.out.println("Hello"); }
protected void bar(){ super.foo(); }
}
class F extends E{
public void foo(){ super.bar(); }
}
You can access the superclass methods from within the subclass itself, e.g.
class A {
void foo() {...}
}
class B extends A {
void foo() {...}
void defaultFoo() { super.foo(); }
}
However, you really shouldn't be exposing overridden methods this way, you should write B.foo() in such a way that works fine for A and B. This is where it is a good idea to use super.foo(); like this:
class B extends A {
void foo() {
super.foo(); //call superclass implementation first
... //do stuff specific to B
}
}
Update: In response to your comment on trying to access the implementation 2 levels up, here's a way of doing it.
class A {
void foo() {
defaultFoo();
}
protected void defaultFoo() { ... }
}
class B extends A {
void foo() {...}
}
class C extends B {
void foo() {
defaultFoo();
... //do other stuff
}
}
This is a healthier pattern of coding what you want to do.
You should probably rethink how you are handling your class hierarchy if you need to place a call to a function that is defined two levels up the hierarchy. Consider writing new methods that are implemented by each subclass in a different way.
I have an interface A, for which I have to supply a few different
implementations. However, those implementations share some helper methods, so
I moved those methods to an abstract base class.
Interface A {
void doX();
}
abstract Class B implements A {
protected void commonY() {
// ...
}
#Override
public abstract void doX();
}
Class C extends B {
#Override
public void doX() {
// ...
}
}
Class D extends B {
#Override
public void doX() {
// ...
}
}
My code works as expected, but I have a few questions:
Should I declare the abstract Method doX() in Class B? Why (not)?
Should I also explicitly declare "implements A" on Class C and D? Why (not)?
I think it would be better to do it as follows:
Interface A {
void doX();
}
abstract Class B {
protected void commonY() {
// ...
}
}
Class C extends B implements A{
public void doX() {
// ...
}
}
Class D extends B implements A{
public void doX() {
// ...
}
}
You shouldn't mix the interface (signature of methods) with the implementation.
Should I declare the abstract Method doX() in Class B? Why (not)?
No. It's an abstract class - defining the interface will mean that all subclasses will need to implement those methods. In other words, it's redundant.
Should I also explicitly declare "implements A" on Class C and D? Why (not)?
No, again - because your superclass (Abstract base class) implements that interface, your concrete subclasses will be guaranteed to implement that interface.
I'll just throw in the other option.
Turn abstract class B into an AUtil class that doesn't implement A. The method signatures may require an additional argument of type A to work with.
C and D implement A, and instantiate an AUtil internally. This does allow C and D to extend other classes.
I agree with JeeBee: consider implementing your helper methods somewhere other than an abstract base class.
If your helper method commonY() only exists in abstract base class B, all classes which implement Interface A will have to also extend base class B in order to take advantage of that implementation of commonY(). But, you might not always want to be forced to extend class B.
Also, what if you want to change the implementation of commonY() in the future? You will then affect lots of implementations of interface A. But if you don't control all these implementations of interface A, you may affect their functionality (in a bad way) without intending to.
Using an abstract base class in this situation may simply take away some flexibility without giving you anything in return.
An abstract class implementing an interface must implement that interface. Specifically, it must have a public method for every method-name-and-signature specified in that interface.
Inheritance is transitive. You do not need to write that class C implements interface A if class C derives class B which implements interface A. However, there isn't much harm to it either.
I would not declare doX() in B and not add "implements A" on C and D because you should not repeat yourself.
The abstract doX() in B adds nothing, as it's already specified by "implements A". The same is true for adding "implements A" to C and D.
The only possible use for those clauses would be documentation: If you want to make it very explicit that C (or D) is-a A, then you could add the implements, but you should be aware that it really doesn't matter to the compiler.