How can I implement a specific method from two different abstract classes?

I want to access all methods (not abstract or abstract) from Class A

So, I extended Class A , but here, in Class B , I want to access all non-abstract methods and only 10 abstract methods - since I don't want to implement the rest of the abstract Class B methods.

Problem

1. I cannot extend Class B because I have already expanded Class A

2.I cannot put these 10 methods inside the interface because I also want to access non-abstract methods from Class B

What should be the right approach to reusing these methods?

class A

 abstract class A{ public void m1(){ //do stuff } public void m2(){ //do stuff } // +30 more non abstract methods public abstract void n1(); public abstract void n2(); // +30 more abstract method } 

class B

 abstract class B{ public void a1(){ //do stuff } public void a2(){ //do stuff } // +30 more non abstract methods public abstract void b1(); public abstract void b2(); // +30 more abstract method } 

class C

 class C extends A{ public void n1(){ //do stuff } public void n2(){ //do stuff } //+30 more abstract methods implemented //But here i want all the non abstract methods and only 10 abstract methods of B } 
+5
source share
1 answer

A serious rejection of the answer here: stop; and step back. Forget about it.

The chances are extremely high that your design is already in very poor condition. Because you should always prefer a complex network of simple classes over a simple network of complex classes.

Inheritance is much more than just writing A extends B It starts with: in this case, any A is-a B. Alone, the number of methods that you specify in your question indicates that your classes do not follow this simple rule; and perhaps they also violate others.

So: don’t waste time to figure out how to add 10 more to the other 30 methods in your class. Take the time to throw everything away; and build an OO model of the real .

You will begin by understanding the problem area; derive useful, useful classes from this. Classes that focus on problem solving. Classes that follow SOLID rules. Or remember the old FCoI concept .

In short: I would consider a class with more than 10 methods to be refactored; but 30 abstract methods; it sounds (sorry) (almost) completely insane.

Change some comments: of course, it is possible that the OP is really a reasonable design; since there are examples of classes that come with many methods (for example, for a typical Swing UI component). But (imho) the likelihood of a β€œbad” design is quite simple when dealing with a large number of abstract methods.

+12
source

Source: https://habr.com/ru/post/1266987/


All Articles