Is a Java interface an abstract class? [duplicate] - java

This question already has answers here:
implicit super-interface in Java?
(4 answers)
Closed 4 years ago.
I'm working through some homework and a question on a previous exam paper asks to name all of the abstract classes in a given UML diagram. Fairly straightforward, I suppose. There are one abstract class and three interfaces. Do these interfaces qualify as abstract classes, in general?

Thing is, while technically interfaces may be represented as classes in languages like Java, I wouldn't consider them classes.
Abstract? Hell yes. Class? No.
Interfaces cannot have constructors, neither properties, fields, function bodies, etc. Interfaces cannot be inherited, they are implemented (again, technically it might be true that implementing an interface is actually inheriting it in specific languages, but that's not my point.) Interfaces are more like 'contracts' as they do not define any behaviour whatsoever like classes.
Now if this is a homework then you shouldn't really argue about these sort of stuff with the teacher. Just check your lecture notes and see if the word "class" is mentioned anywhere in the your teacher's definition of interface.

All interface are indeed abstract
Actually, you can declare an method as abstract within an interface... except any 'checkstyle' tool will tell you the abstract keyword is redundant. And all methods are public.
If a class implements an interface and does not implement all its methods, it must be marked as abstract. If a class is abstract, one of its subclasses is expected to implement its unimplemented methods.
To echo other answers, an interface is not a class.
An interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
Interfaces are not part of the class hierarchy, although they work in combination with classes.
When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface
To better explain why an interface is not a class, consider the following:
1/ an interface is a type used by values
2/ a class is for Objects
3/:
Object a = new Date();
String s = a.toString();
The type of the variable 'a' is Object (which is actually a type notation in Java source code meaning a reference to an Object),
but the class of the object it points to is Date.
The type (Object) only affects what code is valid according to the compiler's type-checking, but not what the code actually does.
The class of the object affects what the code does, so that the a.toString() call in the second line returns a String that looks like a Date, not one that looks like "java.lang.Object#XXXXXXXX".
Since an Interface is a type, it is used for values only, and will not represent what objects will actually do in term of runtime.

In Java though, theres a twist to the tale - all Interfaces in Java extend java.lang.Object! Try adding a method:
public void notify();
in an interface and see what happens..
An Interface extending a Class - Does that make the Interface a Class? Or the Class an Interface?? Uhh-huh.. Guess it was a hack that had to be done to prevent interfaces overriding the definitions in java.lang.Object that implementations of the interface had to extend anyway.

You've only asked about the abstract side, but don't forget the class side - I wouldn't call an interface a class, so even though interfaces are abstract (as per the specification), I still don't think they count as abstract classes. It may be worth explicitly explaining that though :)

Yes, an Interface is implicitly Abstract. Look behind the scenes as to the way it is encoded to a .class file.
Semantics are a funny thing though; under exam conditions "abstract class" would have to literally be compiled from a .java source file using abstract class in the Class' declaration.

An interface contains prototype of methods (i.e Declaration ) not defination but Abstract class can contain defination of method & atleast one Abstract method (method with only prototype)

Interfaces are used to break the Object Inheritance.
They could hold two or more objects of several classes
and classes hierarchies.
Look at an interface as an outlet plug. All classes
implementing an Interface need to have one, the same
way a computer, a coffee machine, a ventilator and a
refrigerator need to have the same device to get
power.

Abstract class looks like interface. Abstract classes can have implementations where as interface can't have any implementations.
Then, there is a question. Can we call abstract class as interface if they only have method signatures?
I think, abstract classes, unlike interfaces, are classes. They are expensive to use because there is a lookup to do when you inherit a class from abstract class.

Related

Is it possible to create a list or ArrayList of interfaces and Generics? [duplicate]

I know, we can not instantiate either an interface or an abstract class in java except using anonymous class method but what is the reason behind it?
You can't instantiate an interface or an abstract class because it would defy the object oriented model.
Interfaces represent contracts - the promise that the implementer of an interface will be able to do all these things, fulfill the contract.
Abstract classes are a similar idea, in that they represent an unfulfilled contract, a promise to be able to do things, except unlike interfaces they have some of their functions or fields defined but need filling in before they can used.
Simply, in a good object oriented program, you should never want to instantiate an abstract class or interface. If you do, the design is probably wrong.
(Anonymous classes are actually non-abstract instantiations, just that they don't need to be given a name, so they appear to be 'raw interfaces' but they're actually an implementation of the interface that has no name. That's my understanding, at least.)
Here is a basic explanation without deeper concept.
Interface has no method implemented, so there is no purpose to instantiate it as 'nothing' will happen when invoke a method
Abstract class can have abstract method declaration, which is like a interface method with no implementation.
You can't instantiate interfaces or abstract classes because some of their methods might not have any definitions.

How are interfaces like Runnable unique?

My understanding of interfaces in java/android is they're used to ensure the member functions are used. E.g. like Runnable which ensures implemented classes use the run() function within Runnable.
However, how are these functions unique? Say there's another interface like Runnable with only 1 member function - let's call it Passable - and it has 1 member function called pass().
How exactly are these 2 interfaces different at all (apart from having different names)?
Or is the names what make them different? E.g. Android detects if the class is called Runnable then it does something different.
Interfaces are not used to define what methods are called.
One of the main function of interfaces is to separate API from implementation.
This means for example that any class that implements Runnable can be used to run in a parallel thread.
The other is to define the type of a class beyond the scope of inheritance.
A quote from effective java:
The Java programming language provides two mechanisms for defining a
type that permits multiple implementations: interfaces and abstract
classes. The most obvious difference between the two mechanisms is
that abstract classes are permitted to contain implementations for
some methods while interfaces are not. A more important difference is
that to implement the type defined by an abstract class, a class must
be a subclass of the abstract class. Any class that defines all of the
required methods and obeys the general contract is permitted to
implement an interface, regardless of where the class resides in the
class hierarchy. Because Java permits only single inheritance, this
restriction on abstract classes severely constrains their use as
type definitions
By implementing the Runnable interface, you aren't telling your code that the run method should be called. You are telling the code that your class is a type of Runnable or literally spelt out, your class is runnable.
One example usage of this could if you were to an abstract class: Plant.
Now you would use this class to define some common properties of plants (such as they need soil), then you would create its subclasses Potato, Rosemary, Dandelion
Now say you want to indicate which of these plants is edible, you could create an intermediary subclass called EdiblePlant that is a subclass of Plant and the superclass of the edible classes. EdiblePlant has a method called eat(), thus you can eat all edible plants.
Now if you want to also have a class Animal and its subclasses Dog, Cow, Pig.
You would again have to indicate which one is edible by a new intermediary class EdibleAnimal, which again would have an eat() method.
I guess it doesn't seem that much work but now what if you want to have Human, who eats?
You would have to have both Human.eat(EdibleAnimal animal); method and Human.eat(EdiblePlant plant) method. Since we can eat both of those.
Instead, we could define an interface Edible that would have a method eat(). This type indicates that Classes (plants and animals) that implement this type can, in fact, be eaten.
Since now we have a common type for edible things we can simply have one eat method on Human, Human.eat(Edible food)
Since we now have a separated interface and implementation we no longer how to think about refactoring/adding new methods to Human, we only have to appropriately implement the Edible type.
I would recommend reading up on how Java works, before starting with Android development, if you don't you can form these kinds of bad theoretical models of how things work such as interface determines what methods will be called and then when it will clash with the actual workings of Java you will be frustrated and won't understand why what you wrote doesn't work as 'expected'.
Two interfaces can have the same "content", like the same number of methods and matching method signatures.
Still they are different because of different names. You might even have interfaces (or classes!) that have the same name, to only deviate in the package name. There are for example multiple different classes out there named Pair.
But interfaces don't determine which methods are called. You write code that picks a method and invokes that, and the fact that some class implements a specific interface simply tells you: "OK, it is a Runnable, so I can and probably want to invoke its run method".
You see, Java is a statically compiled language. That means that you use types to communicate intent. You have some piece of code that is supposed to be called on its own by other code in a uniform, maybe multi threaded context? Then you consider putting that code into a Runnable. That is all there is to this.

What is difference between abstract class with all abstract methods and interface(not technically)

I've been wondering what is the difference between them? Is it only in this: abstract class declares what an object is and interface says what object can do? Or there is something more deeper? Thanks.
Whether it can have fields, whether it can have a constructor, whether any of those methods can be protected/package-private/private, whether subtypes can inherit from other abstract classes/interfaces...that about covers it.
The statement "abstract class declares what an object is" refers to the rule that says that a class may inherit from a base class if it has an "is a" relationship to the base class. So, a Sedan may inherit from Car because a Sedan "is a" Car. But that's only part of the story. Usually, we define abstract base classes to inherit from when we want the abstract base class to contain some functionality that restricts derived classes in what they can do, often by exposing final methods which cannot be overridden. So, a hypothetical mail delivery abstract base class may offer a public final prepareAndSend() method which invokes abstract overridables on itself called stuffEnvelope(), lickEnvelope(), mailEnvelope(), in that order. The derived class may override those methods, but it has no power to change the order in which they will be invoked because prepareAndSend() is final. You can't impose such restrictions with interfaces.
Interfaces, on the other hand, describe "capabilities" or "aspects" that an object may have. An object may have many different capabilities, so it may implement many interfaces.
Note that it may seem that the "is a" relationship can apply to interfaces, but it either only happens in certain contrived examples, or it is an illusion caused by the liberal syntax of the English language; it is not generalizable, in many cases it is not even factual, and that's the reason why there is no rule that says that an object should have an "is a" relationship with each interface that it implements.
So, someone may of course make an "ICar" interface, there is nothing wrong with that, in which case there will inevitably be something that "is a Car", but what you are more likely to see is interfaces like "IDrivable", "IInsurable", "ITaxable", "IFuelConsumer", etc. all of which describe traits. The fact that you can then say "a car is a taxable" is a fluke of the English language; a car does not actually bear an "is a" relationship with "taxable" because "taxable" is not even a thing. So then, whoever came up with that "ICar" usually just meant it as a convenience to combine all the characteristics of a car into one common interface.
In Java, there are no pure abstract classes. A class that declares only abstract methods has concrete methods also, because it is a subclass -- directly or indirectly -- of the concrete Object class.
An interface is a better choice for defining an abstract API. Java allows classes to extend at most one class, but implement multiple interfaces.
From the Java tutorial Abstract Methods and Classes (line breaks added):
However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public.
In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.
The tutorial also recommends cases when an abstract class or interface are desirable. Paraphrased, it recommends abstract classes when you want to share code or non-static, non-final fields, or use access qualifiers other than public. Usually none of these will apply to a pure abstract class.
It recommends interfaces when you want to specify an API that may be implemented by multiple unrelated classes, or want to take advantage of multiple inheritance of interface types.

Should I Program to an Interface or an Abstract Base Class? What exactly does that phrase mean?

In object oriented programming, I have read that you should program to an interface not an implementation but do they mean literal interfaces (no shared code at all)?
Is it okay to program to an abstract base class that would have been an interface except that there were variables in this "interface" that all sub-classes were expected to have? Replicating a variable across sub-classes would have been an inconvenience because if I changed the name of one of the variables in one of the sub-classes I would have to change the name of that variable in all of the sub-classes.
In following the principle of "program to an interface not an implementation", is this okay or would you create another interface on top of the abstract base class and program to that interface?
You want to program to interfaces because it means lower coupling. Note that interfaces in Java are more flexible since they can be implemented by a class anywhere in the class hierarchy unlike abstract classes (as a result of single inheritance). Such flexibility means that your code is reusable to a higher degree.
The important point of "programming to an interface not an implementation" is that of the general principles mentioned above, even if they might cause some minor inconveniences.
Also, even if you program to an interface, you can always implement said interface (or parts of it) by means of abstract classes if you'd like, achieving both low coupling and code reusability at the same time.
It's always okay to program to abstract or even concrete classes, however it's better if you can avoid it.
This discussion might be helpful or this one and of course this one.
Note: C++ doesn't have interfaces. You might argue it doesn't need them.
you should program to an interface not an implementation but do they mean literal interfaces (no shared code at all)?
Possibly. Where it makes sense to do this, it can work very well. Note: in Java interfaces can have code as well.
Is it okay to program to an abstract base class that would have been an interface except that there were variables in this "interface" that all sub-classes were expected to have?
If you need fields in the implementation an abstract class can make sense. You can still use an interface as well.
Replicating a variable across sub-classes would have been an inconvenience because if I changed the name of one of the variables in one of the sub-classes I would have to change the name of that variable in all of the sub-classes.
This is where using an IDE helps. You can change a field, class, method name in all your code with one action.
is this okay or would you create another interface on top of the abstract base class and program to that interface?
You can code your implementation to an abstract class, but the users of that class should be using an interface if possible.
e.g. HashMap extends AbstractMap but implements Map. Most people would use Map not AbstractMap

pure abstract class and interface [duplicate]

This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 8 years ago.
Can anyone tell me what exactly the difference between an completely abstract class and an interface?
An Abstract class can also have all its methods as abstract. An interface has all its methods as abstract. What is the main difference between the two in this scenario?
If there is difference between a pure abstract Class and interface? What is the use of interface? Where interface is being used we can make use of pure abstract class?
To complete the former answers :
An interface is a "contract". If a class implements an interface it have to propose all the services listed in the interface.
An abstract class is a skeleton. It defines a certain way its extended classes will work while letting them some free space (the abstract methods) to be unique.
A pure abstract class doing the same thing as a interface but have the problem of unique extending so, for me, it have no interest
Every interface is implicitly abstract: Every method declaration in the body of interface is implicitly abstract and public.
An abstract class has methods that can contain implementation. Abstract methods can be either public, protected or default access (package visible). Unlike interfaces abstract classes can contain fields that are not static and final.
Also see:
Interfaces vs Abstract classes and the
Java tutorial
In Java and C#, one can use multiple interfaces to derive from and only a single class to inherit from,
One reason to choose pure abstract over interface is to force sub classes to implement particular methods that are implemented by a super class.
For example (in Java),
Say you want all extending classes to implement toString(), equals(), and hashCode().
You could create an interface called ForceSomeMethods for that contract, but those methods are implicitly implemented by Object.
Making ForceSomeMethods a pure abstract class with toString(), etc as abstract methods, all subclasses will be forced to implement those methods.
It's not a very theorotical explaination but, programatically it's all correct
Interface Abstract Class
Extend Class No Yes
Extend Abstract Class No Yes
Implement Interface Yes(Extend Interface) Yes
Variables Public Static Final Public/Protected/Private/static/final/transient/volatile
Contain Non-Public Method No Public/Protected/*Private
Contain Abstract Method Yes Yes
Contain No-Body, Non-Abstract Method Yes No
Contain Defined Method No Yes
Contain Main Method No Yes
*Abstract classes can have private methods, but not abstract private methods.
An abstract class can provide an implementation, i.e. (public, protected, private) method bodies. An interface can just declare public method signatures. These methods have to be realized (in the form of method bodies) by classes implementing the interface.
There are three differences:
Interfaces can only declare public methods (i.e. no protected or package-private visible methods) and can not declare any fields
Subclasses can only extend at most one abstract class, but can implement any number of interfaces
The abstract class can also have implementations for some or all of the methods
I'm just going to address one point (mainly because the other questions have been addressed already):
"Where interface is being used we can
make use of pure abstract class?"
In theory, you could. However, you will lose flexibility and loose coupling to some extent. It's far more preferable to code to interfaces and pass those around, especially in Inversion of Control (IoC) scenarios and from an integration point of view, as this allows far greater extensibility.
Since the question is about pure abstract classes then I'd say the answer is going to be related to inheritance and scope. It's something I've wondered myself many times and this is what I've come up with.
Obviously the features related to multiple inheritance have been answered previously so I won't go in to any of that. Scope is a big one though.
In an interface you can't define a member's access modifiers since they are implicitly public,...you are defining the public interface for it's eventual implementation. There's an important difference there since you can define a protected abstract member in a pure abstract class.
Inheriting from such a class definition would force the inheritor to implement the abstract member but scope it privately to consumers of the class (though it would have to be defined as protected so unless the class was marked as sealed further inheritors would have access).
In essence you can define a private interface using pure abstract classes. Whether that's a good idea is a different question altogether but one good use I've seen it used for is to enforce design patterns and standardize class designs.
HTH
You can use Interface for multiple inheritance, but you can't use abstract class for multiple inheritance.
All the methods in Interface is public by default, by in abstract class, only the methods which you've set as an abstract need to be declared public.
A class can implement multiple interfaces, but only extend from one class (abstract or otherwise). If you need to specify an interface, then you should use an interface, so that classes may implement multiple of your interfaces.

Categories

Resources