Java – is it OK to have an ’empty’ class that extends another class?
Suppose I have a class foo, which has a pile of logic, and another class bar is basically the same However, since Foo and bar are different (but related) entities, I need to make a clear difference from my code (that is, I can judge whether an instance is a foo or a bar)
When I fought together, I didn't have much idea. I ended the following points:
public class Foo { /* constructors,fields,method,logic and what-not */ } public class Bar extends Foo { /* nothing here but constructors */ }
Is this all right? Is it best to make bar a compound course? For example:
public class Bar { private Foo foo; /* constructors and a bunch of wrapper methods that call into foo */ }
Even under such circumstances, there are some low-tech things:
public class Foo { /* constructors,logic and what-not */ private boolean isABar; // Could be an enum }
What's your opinion? How do you handle these "tag classes"?
As an example of how my code might want to treat Foo and bar, my code will need to be able to look like list & foo > and list < bar > A foo cannot enter the list < bar > and vice versa
Solution
In my opinion, it is better for Foo and bar to classify a common ancestor class (possibly abstractfoo), which has all functions What is the difference in behavior between Foo and bar? The difference code is regarded as an abstract method in abstractfoo instead of using if statement in the code
Example: not like this:
if (foo instanceof Bar) { // Do Bar-specific things }
Do it in this way.
class Bar extends AbstractFoo { public void specialOp() { // Do Bar-specific things } } // ... foo.specialOp();
The advantage of this method is that if you need a third class, it's like foo, but there's a little difference. You don't need to go through all the code and add and edit all the if statements
The above is the Java compiled by programming house for you - is it OK to have an 'empty' class that extends another class? I hope this article can help you solve Java - is it OK to have an 'empty' class that extends another class? Program development problems encountered.
If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.