Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Interface vs Abstract Class (regarding fields)

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 :)

like image 960
Chris Avatar asked Jan 20 '09 17:01

Chris


People also ask

Can abstract class have fields Java?

Class MembersAn abstract class may have static fields and static methods. You can use these static members with a class reference (for example, AbstractClass.

Can Java interface have fields?

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.

Can interface class have fields?

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 .

Can abstract classes have instance fields?

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).


1 Answers

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.

like image 54
Richard Campbell Avatar answered Oct 12 '22 22:10

Richard Campbell