From what I have gathered, I want to force a class to use particular private fields (and methods) I need an abstract class because an interface only declares public/static/final fields and methods. Correct??
I just started my first big java project and want to make sure I'm not going to hurt myself later :)
Class MembersAn abstract class may have static fields and static methods. You can use these static members with a class reference (for example, AbstractClass.
A Java interface is a bit like a Java class, except a Java interface can only contain method signatures and fields. A Java interface is not intended to contain implementations of the methods, only the signature (name, parameters and exceptions) of the method.
An interface can't contain instance fields, instance constructors, or finalizers. Interface members are public by default, and you can explicitly specify accessibility modifiers, such as public , protected , internal , private , protected internal , or private protected .
Abstract classes can have instance variables (these are inherited by child classes). Interfaces can't. Finally, a concrete class can only extend one class (abstract or otherwise).
It's fairly common to provide both, so that you end up with:
public interface Sendable {
public void sendMe();
}
and
public abstract class AbstractSender implements Sendable {
public abstract void send();
public void sendMe() {
send(this.toString());
}
}
That way, anyone who is happy with the default implementation in the abstract class can quickly subclass it without rewriting a lot of code, but anyone who needs to do something more complex (or who needs to inherit from a different base class) can still implement the interface and be plug-and-play.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With