What I mean is:
interface B {...}
interface A extends B {...} // allowed
interface A implements B {...} // not allowed
I googled it and I found this:
implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible.
However, interface is an 100% abstract class, and an abstract class can implement interfaces (100% abstract class) without implement its methods. What is the problem when it is defining as "interface" ?
In details,
interface A {
void methodA();
}
abstract class B implements A {} // we may not implement methodA() but allowed
class C extends B {
void methodA(){}
}
interface B implements A {} // not allowed.
//however, interface B = %100 abstract class B
implements means implementation, when interface is meant to declare just to provide interface not for implementation.
A 100% abstract class is functionally equivalent to an interface but it can also have implementation if you wish (in this case it won't remain 100% abstract), so from the JVM's perspective they are different things.
Also the member variable in a 100% abstract class can have any access qualifier, where in an interface they are implicitly public static final.
implements means a behaviour will be defined for abstract methods (except for abstract classes obviously), you define the implementation.
extends means that a behaviour is inherited.
With interfaces it is possible to say that one interface should have that the same behaviour as another, there is not even an actual implementation. That's why it makes more sense for an interface to extends another interface instead of implementing it.
On a side note, remember that even if an abstract class can define abstract methods (the sane way an interface does), it is still a class and still has to be inherited (extended) and not implemented.
Conceptually there are the two "domains" classes and interfaces. Inside these domains you are always extending, only a class implements an interface, which is kind of "crossing the border". So basically "extends" for interfaces mirrors the behavior for classes. At least I think this is the logic behind. It seems than not everybody agrees with this kind of logic (I find it a little bit contrived myself), and in fact there is no technical reason to have two different keywords at all.
However, interface is 100% abstract class and abstract class can
implements interface(100% abstract class) without implement its
methods. What is the problem when it is defining as "interface" ?
This is simply a matter of convention. The writers of the java language decided that "extends" is the best way to describe this relationship, so that's what we all use.
In general, even though an interface is "a 100% abstract class," we don't think about them that way. We usually think about interfaces as a promise to implement certain key methods rather than a class to derive from. And so we tend to use different language for interfaces than for classes.
As others state, there are good reasons for choosing "extends" over "implements."
Hope this will help you a little what I have learned in oops (core java) during my college.
Implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible. An interface can however extend another interface, which means it can add more methods and inherit its type.
Here is an example below, this is my understanding and what I have learnt in oops.
interface ParentInterface{
void myMethod();
}
interface SubInterface extends ParentInterface{
void anotherMethod();
}
and keep one thing in a mind one interface can only extend another interface and if you want to define it's function on some class then only a interface in implemented eg below
public interface Dog
{
public boolean Barks();
public boolean isGoldenRetriever();
}
Now, if a class were to implement this interface, this is what it would look like:
public class SomeClass implements Dog
{
public boolean Barks{
// method definition here
}
public boolean isGoldenRetriever{
// method definition here
}
}
and if a abstract class has some abstract function define and declare and you want to define those function or you can say implement those function then you suppose to extends that class because abstract class can only be extended. here is example below.
public abstract class MyAbstractClass {
public abstract void abstractMethod();
}
Here is an example subclass of MyAbstractClass:
public class MySubClass extends MyAbstractClass {
public void abstractMethod() {
System.out.println("My method implementation");
}
}
Interface is like an abstraction that is not providing any functionality. Hence It does not 'implement' but extend the other abstractions or interfaces.
Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.
Related
Not sure why I would need to, but would it be possible in Java to have an abstract super with a concrete subclass that has an abstract sub of its own? Presuming that abstract would eventually have concrete classes under it.
Yes, you can have both concrete class extending abstract class and vice versa - abstract class extending concrete class.
public abstract class A {
}
public class B extends A {
}
public abstract class C extends B {
}
No that is a really bad practice. Event if Java allows it, it doesn't have any sense from the point of view of UML diagrams.
A class is abstract if it doesn't implement all the behavior expected. Then in the concrete sub-class, it is concrete because it implements all the behavior needed. Then, having an abstract sub-sub-class doesn't make any sense. It is a specialization of a concrete class, meaning it has all the protocol needed for that object.
In other terms, a specialization of a concrete concept can't be abstract.
I am new to Java. What is the difference between Abstract data type and Interface.
For Example We have a ListADT
interface MyListADT<T> {
void add(T var);
void add(T var,int pos);
void display();
T remove(int pos);
void clear();
boolean contains(Object o);
}
Where we are defining the ADT as an interface. NoW What is the difference between ADT and Interface Or ADT is an Interface
There seems to a confusion in this Q&A. The question was about "Abstract Data Type and Interface" and most of the answers concetrating about "Abstract Classes".
The terms 'abstract data type' and abstract class refer to two entirely different concepts, although both of them use the word 'abstract'. An abstract data type is a self-contained, user-defined type that bundles data with a set of related operations. It behaves in the same way as a built-in type does. However, it does not inherit from other classes, nor does it serve as the base for other derived classes. If you search about it in wiki you would see "An abstract data type is defined as a mathematical model of the data objects that make up a data type as well as the functions that operate on these objects. There are no standard conventions for defining them. A broad division may be drawn between "imperative" and "functional" definition styles." For example, in Java we have List interface. It defines a data structure with set of method to operate on but wont provide any implementaion as such.
In contrast, an abstract class is anything but an abstract data type. An abstract class is a class that is declared abstract — 'it may or may not include abstract methods'. Abstract classes cannot be instantiated, but they can be subclassed. It is not a data type. An abstract class is merely a skeletal interface, which specifies a set of services that its subclasses implement. Unfortunately, the distinction between the two concepts is often confused. Many people erroneously use the term abstract data type when they actually refer to an abstract class.
In my opinion Interfaces are Java's way of implementing "Abstract Data type"
You can read about "Abstract Data Type" in Wiki. In additiona to that if you want to know more about abstract data type in java you could refer this link, http://www.e-reading.ws/bookreader.php/138175/Abstract_Data_Types_in_Java.pdf, its really good.
Most of you might be familiar with abstract classes, Still you could read about it from http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
To add up to this confusions, Java 8 introduced something called "Default Methods", by which we could actually give implementations for methods in interface. To eliminate that confusion you can refer this stackoverflow question Interface with default methods vs Abstract class in Java 8
Try to think about it like this:
Java interface is a type, which boils down to a set of method signatures. Any type, willing to be referenced as interface must provide implementation for these signatures. In reality, there is no behaviour contract. Your implementation can do nothing and still be 'implementing' an interface.
Java abstract class is a type, with partially specified behaviour whose internal implementation for some reason must be specified in his inheritor. This class does have behaviour, which can be redefined/specified in his inheritors.
ADT is a set of expected behaviours. You assume, that after calling adt.remove(element) you call adt.get(element) and receive null.
The answer to your question is: just an interface is not enough to be an ADT.
Everything, that correctly implements your interface MyListADT<T> is an ADT. Its external behaviour must conform the ADT concept. This means, that to be considered as ADT, your type must carry implementation, which results either in abstract class or a normal class. For example: java.util.List<T> is an interface for an ADT, but java.util.ArrayList<T> and java.util.LinkedList<T> are actually ADTs, because their actual behaviour does conform the ADT concept.
The combination of data together with its methods is called an Abstract Data Type(ADT).
A Java Interface is a way to specify ( but not implement) an ADT.
It specifies the names, parameters, and return types(ie, header) of the ADT methods.
The interface does not specify the data fields (except public constants), as that is an implementation detail.
A Java Interface specifies the requirements of an ADT as a contract between the service provider ( class that implements the ADT) and the client (the user of the class).
As per [wiki] http://en.wikipedia.org/wiki/Abstract_data_type
In computer science, an abstract data type (ADT) is a mathematical model for a certain class of data structures that have similar behavior; or for certain data types of one or more programming languages that have similar semantics. An abstract data type is defined indirectly, only by the operations that may be performed on it and by mathematical constraints on the effects (and possibly cost) of those operations.
For Java programming language
you can take Java's List interface as an example. The interface doesn't explicitly define any behavior at all because there is no concrete List class. The interface only defines a set of methods that other classes (e.g. ArrayList and LinkedList) must implement in order to be considered a List.
but the bottom line is that it is a concept
In java-
interface can have only abstract method which means you can only declare the method i.e . method can have any default implementation.but abstract class can have both abstract or complete method.
if the class you are extending is abstract then your child class should either be declared as abstract or should implement all abstract method of super class.
In case -in interface you can implement as many interface you want.Here also you should implement all the abstract method of all the interfaces in your class or it should be declared as abstract.
follow these link
http://javapapers.com/core-java/abstract-and-interface-core-java-2/difference-between-a-java-interface-and-a-java-abstract-class/
http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface
What is the difference between an interface and abstract class?
For more clearance.
Syntax and examples
syntax of abstract class
public abstract class MyAbstractClass
{
//code
public abstract void method();
}
example of abstract class
public abstract class Animal
{
abstract void walk();
}
public class Dog extends Animal
{
void walk()
{
//Implementation is done here
}
}
syntax of interface
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}
example of interface
interface Animal {
public void eat();
public void travel();
}
implementing interface
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}
extending interface
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
extending multiple interfaces
public interface Hockey extends Sports, Event
extends and implements Both
interface A can extends interface B
class A can extends class B
class A implements interface A
class A extends class B implements interface A
The combination of data with its methods is called an Abstract Data Type (ADT).
A Java Interface is a way to specify an Abstract Data Type (ADT).
You can declare a class as abstract when it contains zero or more abstract methods or When an interface is implemented to a class where not all methods are not implemented.
What is the difference between Abstract data type and Interface.
Variables declared in a Java interface is by default final. An
abstract class may contain non-final variables.
Members of a Java interface are public by default. A Java abstract
class can have the usual flavors of class members like private,
protected, etc..
check this link for info
I am trying to use extends keyword in place of implement to use interface is it possible in java.
Interface myinterface
{
//methods
}
public class myclass extends myinterface
{
//methods
}
Tell me the purpose of these two words extends and implements. why class is not use implement keyword to inherits the class from other class
Think about the two words and what they are telling you.
Implements - means to put something into effect. An interface is regularly defined as a contract of what methods a class must have, or implement. Essentially you are putting that contract into effect.
Extends - means to make longer. By extending the class you are basically making it longer by also including all the methods of the extended class.
Two different words that are giving you, by definition, two different abilities within your code.
Interface cannot be extended but rather implemented.
Interfaces can contain only constants, method signatures, and nested types. That is they only represent an abstraction of your model or can simply contain a list of constants.
Interfaces support inheritance. You can have for instance :
public interface InterfaceA extends InterfaceB
If you really want to extend from a class and have some abstract methods you can use an abstract class as :
public abstract class AbstractA {
public abstract void myAbstractMethod;
}
public class A extends AbstractA {
#Override
public abstract void myAbstractMethod {
// your code
}
}
No, you have to use implements with interfaces.
You can however make an abstract class if you absolutely need to use extend.
Classes cannot extend an Interface. They can only implement them. Only an Interface can extend another Interface just like only a Class can extend another Class.
Tell me the purpose of these two words extends and implements.
When a class extends it inherits attributes and behaviour i.e. methods from the class it extends from. A class can only extend from one class since multiple inheritance isn't supported in Java.
When a class implements it provides behaviour i.e. implementation for the methods defined as stubs (just the signature without code) in the Interface it implements. A class can however implement multiple interfaces.
When an Interface extends another Interface its simply adding more methods to the list of methods that a Class implementing it needs to provide implementation for.
As others, most succinctly #Stefan Beike, have said: no, you can't use extends when you mean implements. What you can do, if desired, is to add an in-between abstract class which implements your interface, and then extend that class. Sometimes this is done with empty implementations of the interface's methods, and then you only need to override the methods of interest in your child class. But it can be a purely abstract class if all you want is to use extends where implements would otherwise be called for.
Extends - is used by a class for extending some features of another class, so that same method or fields can be reused. Basic example can be :
class Animal
{
private String name;
public void setName(String name)
{
this.name = name;
}
public int getLegs()
{
return 2;
}
}
class Elephant extends Animal
{
public int getLegs()
{
return 4;
}
}
Now, setter is reused and extends doesn't mandate it to be overriden, but as per requirement any method can be overriden also, as getter in our case.
Implements - A class can implement an interface. This helps in achieving abstraction. any method in interface needs to be implemented by any class that is implementing the interface. It is mandatory, until or unless class is abstract, in which case any other concrete class should implement the unimplemented methods.
So, a class can extends other class for reusing functionality, and a class can implement an interface to enforce some functionality that a class must provide by itself.
Now, why interface extends interface, I am also not sure, may be its because sub interface will extend the methods of super interface and it will enforce implementation of methods in super interface on class that is implementing the sub interface. As super interface does not enforce implementation on sub interface, so implements can not be used.
I hope I am clear.
class extends class (Correct)
class extends interface (Incorrect) => class implements interface (Correct)
interface extends interface (Correct)
interface extends class (Incorrect) (Never possible)
This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Abstract class vs Interface in Java
(15 answers)
Closed 2 years ago.
Please tell me situation where interface is better than abstract class in Java
I think you have misunderstood the real meaning of interface and abstract class.
Interface is programming structure where you define your functions/services that you want to expose to public or other modules. Kind of a contract where you promise that you are providing some functionalities or services, but hiding the implementation so that implementation can be changed without affecting your contract.
Abstract class is a partially implemented class and it has no real meaning other than serving as a parent for multiple child classes those with real meaning. Abstract class is special parent class that provides default functionalities to multiple child classes. it is created as abstract because of unavailability of suitable concrete parent class.
In a good design, you should always create an interface. But abstract class is optional. If you can not find a concrete parent class, create an abstract class and implement the interface then provide default implementations for those interface functions (if possible) otherwise mark them as abstract functions and leave the implementation to the child classes.
A class can implement multiple interfaces, but it can only extend one abstract class.
Interfaces allow the creation of proxies that encapsulate a concrete class. This is used extensively by frameworks in order to intercept method calls to the concrete class (e.g., for starting a transaction before the method is executed or to write to the log).
Use an interface when you don't need to provide any default implementations.
Here is a nice link comparing the two: Interface vs. Abstract Class
You can only have one direct abstract superclass. Therefore, interfaces are useful if you need to expose two or more interfaces.
Java doesn't have multiple inheritance; thus, you cannot have a class that implements two abstract classes at once. For instance, if you want a MouseListener and an ActionListener in a same class, you have to do it the interface way.
An interface is better than a abstract class when you want multiple classes to implement that interface and when you don't have to inherit default behavior.
In order to provide WebServices or do JMock tests you dont need the actual implementation, you just need an interface definition. Think about it, there is no need to return the implementation to a third party when all they need to do is call your API.
When you need to implements in any class because interface can be implements in any class or interface but abstract class cant do that e.g. in Applet always Applet class extend in our Applet Application in this case we cant extend the abstract class.
Abstract Class : Define or Declare a method which is more important. Example:
Vehicle must have shape and engine. So we put this behaviour is in Abstract class.
abstract class Vehicle {
abstract void shape();
abstract void engine();
}
Interface Class : Other than that properties like move, honk, etc. So interfaces that provide additional behaviour to your concrete class.
interface Honk{
void honk();
}
interface moveable{
void move();
}
class Car extends Vehicle implements Moveable {
#Override
void shape() {
System.out.println("car's shape");
}
#Override
void Engine() {
System.out.println("car's engine");
}
#Override
void move() {
System.out.println("car's can move");
}
}
But I didn't implements Honk behaviour. If you want you can implements multiple interfaces.
Are there some practical programming situations for someone to declare a class abstract when all the methods in it are concrete?
Well you could be using a template method pattern where there are multiple override points that all have default implementations but where the combined default implementations by themselves are not legal - any functional implementation must subclass.
(And yes, I dislike the template method pattern ;))
An abstract class is a class that is declared abstract - it may or may not include abstract methods. They cannot be instantiated so if you have an abstract class with concrete methods then it can be subclassed and the subclass can then be instantiated.
Immagine an interface whose declared methods usually show the same default behavior when implemented. When writing a class that needs to support the interface you have to define said default behavior over and over.
To facilitate implementation of your concrete classes you might want to provide an abstract class providing default behavior for each method. To support the interface in a concrete class you can derive from the abstract class and override methods if they deviate from the standard behavior. That way you'll avoid the repeated implementation of the same (redundant) default behavior.
Another possible use case is a decorator which delegates all calls to the wrapped instance. A concrete decorator implementation can override only those methods where functionality is added:
public interface Foo {
public void bar();
}
public abstract class FooDecorator implements Foo {
private final Foo wrapped;
public FooDecorator(Foo wrapped) { this.wrapped = wrapped; }
public void bar() { wrapped.bar(); }
}
public class TracingFoo extends FooDecorator {
//Omitting constructor code...
public void bar() {
log("Entering bar()");
super.bar();
log("Exiting bar()");
}
}
Although I don't really see the necessarity to declare FooDecorator as abstract (non-abstract example: HttpServletRequestWrapper).
Previous answers already hit the main issues, but there's a minor detail that might be worth mentioning.
You could have a factory that returns instances of (hidden) subclasses of the abstract class. The abstract class defines the contract on the resulting object, as well as providing default implementations, but the fact that the class is abstract both keeps it from being instantiated directly and also signals the fact that the identity of the "real" implementation class is not published.
Wondering why no one has pointed to the Practical Example of MouseAdapter:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/MouseAdapter.html
An abstract adapter class for receiving mouse events. The methods in
this class are empty. This class exists as convenience for creating
listener objects.
Nice question :)
One thing is for sure ... this is certainly possible. The template suggestion by krosenvold is one good reason for doing this.
I just want to say that a class must not be declared abstract just for preventing it's instantiation.
This is referred in the Java Language Specification Section 8.1.1.1
When you have an important class but the system cannot create an instance fo this class, because
this class is parent of a lot of classes of the system;
this has a lot of responsability (methods used by a lot of class) for domain's requires;
this class not represents a concrete object;
Servlet Example:
All methods are concrete,
but the base class is useless by itself:
DeleteAuthor.java
Abstract class with concrete doGet method.
doGet calls file pointed to in protected string sql_path.
sql_path is null.
DeleteAuthorKeepBook.java
extends abstract class DeleteAuthor
sets sql_path to delete_author_KEEP_BOOK.sql
DeleteAuthorBurnBook.java
extends abstract class DeleteAuthor
sets sql_path to delete_author_BURN_BOOK.sql