Abstract class with little used abstract method - should I make concrete? - java

Let's say I have a class called GUIElement described by this code:
public abstract class GUIElement {
public abstract void onScroll();
//Other methods such as getX(), getY(), onClick() etc.
}
All GUI elements that extend this are obviously forced to write concrete code for onScroll provided they are a concrete class, but very few actually use this onScroll method as it is only handy in something like a long GUIText block.
My question is then, what is the best practice in this situation? Continue to force all child classes to write code even when mostly it will be empty, or make it concrete like so:
public abstract class GUIElement {
public void onScroll() {}
//Other methods such as getX(), getY(), onClick() etc.
}
and have the few classes that use it just override it.
Or maybe there are other, better alternatives?

If only a few classes need to implement the method, then the Adapter Pattern is a good choice. Which is, what your second approach basically is. Have an empty implementation in the parent class and only those child classes that need this functionality can override it, but they're not forced to do so.
Take a look at the MouseAdapter in the AWT package for instance. It implements the MouseListener interface, but leaves all methods empty. Child classes then can choose whether to override those methods or not.

Let's say I have a class called GUIElement described by this code:
public abstract class GUIElement {
public abstract void onScroll();
//Other methods such as getX(), getY(), onClick() etc.
}
All GUI elements that extend this are obviously forced to write concrete code for onScroll provided they are a concrete class, but very few actually use this onScroll method as it is only handy in something like a long GUIText block.
In an abstract class methods should be abstract because concrete methods in this abstract class use them, e.g.:
public abstract class GUIElement {
public void onScroll(){
// do stuff
SomeObject retunValue = calculateInSomeChiledClass();
// do other stuff
}
potected abstract SomeObject calculateInSomeChiledClass();
}
An abstract class should not have abstract methods for any other reason.

Make an empty concrete method is a way but it has a consequence as it doesn't force new declared class to override it.
If this consequence is not a drawback for you, using this way is fine.
Otherwise, if you want to be sure that subclasses specify explicitly how to implement the operation, you should keep the method as abstract and implement them when it is required and throwing UnsupportedOperationException or an empty implementation in the subclasses where the operation is not supported.
Both solutions are acceptable.
Follow the one or the second depends on the point that you want to stress on for your subclasses : simple API or explicit behavior to define.

Related

Is it possible to overload abstract methods in an abstract Java class, but implement only one of the overloaded methods in subclass?

I have an abstract class (showing only the relevant parts) with two overloaded methods.
abstract public class Component {
...
abstract protected void createPhysics();
abstract protected void createPhysics(Comp1D[] comp1DS);
...
}
In the subclasses which extend this abstract class I only want to use either the one with arguments or the one without, but never both of them. For example
public class Comp1D extends Component{
...
protected void createPhysics(Comp1D[] comp1Ds){
...
}
}
and
public class Comp3D extends Component{
...
protected void createPhysics(){
...
}
}
Of course this won't compile this way since the other createPhysics method is not implemented in the subclass. My quick and dirty solution would be to implement both methods in subclasses, but the unused method would have empty body.
Is there a more elegant way to solve it in Java 8?
With abstract methods, there is not. And on a syntactical level, it would not be sound either. If one has a Component, one can call both methods. How should one know which one is implemented and which one is not?
One could define both method in the abstract class and let them throw, for example, an UnsupportedOperationException, thus forcing sublcasses to override (at least one of) those methods if they wish to not throw such an exception. This, however, seems like a workaround for another problem.
I would suggest re-evaluating the overall architecture of that section and find another solution to the problem. For example, maybe two separated classes and handler for those classes would yield a cleaner architecture.
The question is, why do you want to use an Abstract class here. What if you plan to use an interface, with default implementations. You can implement the interface and override only the required method
The idea of using abstract class is when you want to define common method signatures in the class and force sub-classes to provide implementation for such methods. From this point of view the way you are trying to implement abstract class doesn't make much sense.
You can also use abstract class to define a base type to support O-O features like polymorphism and inheritance and i think this is what are you trying to do .
If this is the case i suggest to declare an abstract class without abstract methods or declare an interface with default implementation for both methods and then you can override in implementation classes.
As #Turning85 pointed out, such an implementation would not make much sense.
Either you want to give your successor classes the flexibility to implement both of the methods according to their own specific needs or you want to take this complexity away from them and implement the whole logic in the abstract class, where you could have something like this:
abstract class Component() {
protected void createDefaultPhysics() {
//implement
}
abstract protected void createPhysics(Comp1D[] comp1DS);
}
and your concrete classes:
public class Comp1D extends Component{
protected void createPhysics(Comp1D[] comp1Ds){
if(comp1Ds == null) {
createDefaultPhysics();
}
}
}

java abstract class inheritance

i have an abstract class,this class is extended in her subclasses:
i implementend one method on this abstract class and i made the other method abstracts
the implemented method is a general method that every subclass object has to access on it.So i decided to implement it on the abstract class,avoid implementing the same method on each subclass.
little example:
public abstract class Foo{
//plus constructor and other stuff.
public abstract void differentTypeOfImplementation();
public void doSomething(Foo foo){
//do something with the generic Foo object passed
}
}
i want your opinion on this type of implementation,
regards.
This question is probably too open ended, but your solution is perfectly fine.
The alternative is that you can make an Interface with differentTypeOfImplementation(), and then a utility class with doSomething. That way, your subclasses can also extend from other classes. However, if subclasses may occasionally override doSomething, or if doSomething require accessing internal states of the object, then what you have is perfectly valid.
Implementing a method in an abstract class is very much valid and acceptable design. If this method implementation is necessary for all its subclasses then this is the way to go. In your example however - the signature of the method makes it little fishy - it looks like you are not using the super class state in any way . That means you could as well declare this method as static.

interface and overriding the methods of the interface

I'm 13 and quite new to java. What I can't seem to figure out is how NOT to implement overriding methods in a class from an interface because they are references. I don't want to make a new copy, and I can't just make (insert Class here) extend (the class the interface gets some of its methods from). So I implement it and what do i get?
err: The type Threadmanager must implement the inherited abstract method (the method)
and then it has a list, one of which says "implement uninherited methods".
But I dont want to implement any methods! I want to use them!
Threadmanager tm;
AwtUtils manager = tm;
manager.drawImage(/*params*/)
The above is what i want, the following is what i don't want:
#override
public void drawImage(/*params*/){
...
}
I don't want to redefine the methods in the interface, simply just use them. and I cant have class ThreadManager extends Debugger(.java) because it already extends something. I thought interfaces were a way you could use those methods in another class without inheriting them through "class foo extends bar"
By the way, all the methods referenced in the interface are references to methods in my class Debugger.java which doubles up as a debugger and the game library.
You cannot use methods from an interface. An interface has no code, only definitions. Think of it as a functionality contract that classes implementing it have to fulfill.
For example
public interface Example {
public void method1ToImplement();
public int method2ToImplement(final String input);
}
This is a contract that all classes implementing this interface must fulfill. This means any instantiable class that implements Example has to implement public void method1ToImplement() and public int method2ToImplement(String). This is because you're stating this class fulfills this functionality, so you must implement this funcionality because as of now there's no code for this functionality in your class since the interface contains no code. For example, you cannot use the methods in List, in fact you cannot even create a new List because it's an interface. But you can create and ArrayList and use its methods because it's a non-abstract class implementing the List interface.
Maybe you're confused because you saw somewhere else you can use already implemented methods, for example toString() (which is already implemented in all classes). This is because this method is not defined in an interface but by a parent class (in case of toString() it's Object that implements it).
TL;DR: A class implementing an interface must implement its methods unless it's abstract.
If I'm understanding you right, you want a class to implement an interface, but don't implement its methods. If that's so, you cannot. Implementation of interface methods is mandatory, unless you're writing an abstract class.
I'm guessing there's something missing on your question, so please, provide some code of your Interface and Class so that we could give you a better answer.
I think you're confused about what an interface does. An interface simply defines a contract such that any object which implements the interface must define the methods in the interface. If you have an abstract class, then you must implement the abstract methods of said class for any class that extends the abstract class. The only exception to this is when you extend from a class that has already implemented the abstract methods or interface and you don't want/need to redefine them for subclasses.
You say that you don't want to implement the methods, you just want to use them, but you can't use methods that don't exist. Implementing an interface does not magically define the logic in the methods in the interface--that is your job. Again, it simply states that any objects that implement the interface will have the interfaces' methods defined.
One of the nice things about interfaces is the following: Let's assume that we have a collection of objects that all implement a particular interface, then we can call any method from the interface on all those objects. NB: we can group said objects together by having an array, ArrayList, or what have you that take the interface as the type parameter, ie ArrayList<MyInterface>
More specific example:
Let's consider a Shape interface that solely includes the header for an area method. We can have a bunch of difference types of shapes that implement the Shape interface (circles, squares, etc). In each shape class, we define a method to get the area for said shape. Now, if we have an ArrayList<Shape> shapes =... we can put different types of shapes into that list and do the following:
for (Shape s : shapes)
{
System.out.println(s.area());
}

java - unique difference between abstract class and concrete class

I know few differences between abstract class and concrete class. I know that you can't create an instance with abstract class unlike concrete class, abstract class can have 'abstract' methods.
But i have an example like the following. A lot of times, we see the following examples at work. I will just skip some common methods that can be defined in the Parent class.
public abstract class Parent {
public void init() {
doInit();
}
public abstract void doInit();
}
public class Child extends Parent {
public void doInit() {
// implementation
}
}
I think that we can do the same thing with a concrete class like the following.
public class Parent {
public void init() {
doInit();
}
public void doInit() {
// Empty
}
}
I am curious to see if there is any unique situation that we have to use abstract class. Is there any significant difference during runtime with the above example?
Thank you.
The reason to use abstract class in this situation is to force everyone inheriting your base class to override the abstract doInit method. Without the class and the method being abstract, they may forget to do so, and the compiler would not catch them.
In addition to this pragmatic purpose, abstract classes provide a powerful way to communicate your design idea to the readers of your code. An abstract class tells the reader that the methods inside provide some common implementation for a group of related classes, rather than implementing a single concept that you are modeling. Very often communicating your intent to your readers is as important as it is to write correct code, because otherwise they might break something while maintaining your code.
It is customary in Java to call abstract classes Abstract...; in your example that would be AbstractParent.
Of course you can do it that way, but it all depends on the right business logic.There might arise a situation where you'd want to enforce a policy on people extending your code.
For example, I write an Employee class and you extend my class for writing a ProjectManager class. But suppose the business does not allow direct instantiation of Employee (like I said, just an example). So I declare my Employee class as abstract, thereby enforcing upon all extenders (read:you) of my class the rule that they can't instantiate Employee directly. (It will happen indirectly through the inheritance chain, of course, i.e. parent objects are created before child objects.)
Used properly, a person at place A controls how another person at place B will code.
A concrete class is one which has implementation (code inside) for all the methods. It does not matter whether it is derived from some other class.
public abstract class IAmAbstract{
public void writeMe(){
System.out.println("I am done with writing");
}
}
public class IAmConcrete extends IAmAbstract{
public void writeMe(){
System.out.println("I am still writing");
}
}
Abstract classes have a variety of useful properties in use with software design.
Other than the obvious differences, such as being unable to be instantiated and being able to hold abstract methods. They are useful for defining common, yet overridable, functions, holding static methods that deal with it's children in a logical manner.
My favorite is the abstract factory pattern though.
By making a factory that is the parent of all the classes it may create, it can force functionality required for creation, this actually causes an odd artefact where technically tighter-coupled code is actually easier to maintain.

Java: Make a method abstract for each extending class

Is there any keyword or design pattern for doing this?
Please check the update
public abstract class Root
{
public abstract void foo();
}
public abstract class SubClass extends Root
{
public void foo()
{
// Do something
//---------------- Update -------------------//
// This method contains important code
// that is needed when I'm using a instance
// of SubClass and it is no instance of any
// other class extending SubClass
}
}
public class SubberClass extends SubClass
{
// Here is it not necessary to override foo()
// So is there a way to make this necessary?
// A way to obligate the developer make again the override
}
Thanks
If you are doing this, then you are probably abusing inheritance; inheritance, contrary to popular myth, is not intended for making custom hooks/handlers, but rather to enable alternative implementations.
If you want your user to provide some sort of function/hook/callback, then you should define an interface that provides just those methods that you need your user to define. Then you should require the user to pass in an instance of that interface to your object's constructor or passed into the function that needs it.
Aggregation, delegation, and composition are frequently better and safer design patterns than inheritance; forcing other users to inherit from your class, is incredibly risky, as it provides the user with many opportunities to violate the contract of your class or to invalidate the invariant of your base class.
If every class subclassing SubClass has to override foo() then why provide an implementation at all in SubClass? You can simply remove the method definition from SubClass and then all subclasses will be forced to provide an implementation.
If you really want to, you can re-declare foo as abstract.
public abstract class SubberClass extends SubClass
{
public abstract void foo();
}
Instead of overriding foo() in SubClass, create a new method fooImpl() and leave foo() abstract. This way, all classes must implement foo() but you can simply implement it by calling fooImpl() if that is already enough.
Yeah it is not necessary to override foo() in SubberClass.
You can't have it both ways. You can't provide a method with a default implementation AND require child classes override it. Instead of declaring the method as abstract in Root, you could define an interface (IFoo) with the method declared and then provide an abstract class that implements the interface. That would still require a concrete child class but would not require a method override.
Most of the time you see this type of pattern, an interface is used to define a set of methods and an abstract base class provides some default implementations for some but not all methods from the interface. This requires the concrete child class to provide code for the remaining methods and the option to override the default behaviors.
In any case, you can't provide a default behavior for a single method and require child classes to override that same method.

Categories

Resources