Abstract Data Type and Interface - java

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

Related

Concrete class implementing interface with lower access

Why did java make interface allow only public abstract methods?
Why are interface methods always public and not allow protected. Where in abstract class can implement protected abstract methods.
Abstract class can make lower access abstract methods right? An interface is an abstract data type that defines a list of abstract.
Can someone explain to me why it was implemented like that?
public abstract class Animal{
protected abstract void printName();
}
---Assume As Separate file ---
public class Lion extends Animal{
protected void printName(){}
}
This answers the question which eventually popped up in your comment:
why is interface methods always public and not allow protected. where in abstract class can implement protected abstract methods or even lower
It doesn't make sense to make an abstract method in an interface anything other than public, because then it wouldn't be possible for an implementing class to see it. Actually, in Java 9, there is such a thing as private interface methods. But, private interface methods cannot also be abstract, because these two modifiers mean different things. Private methods in Java 9 interfaces are intended to be consumed within the interface, e.g. by default methods. So it makes sense to have a private interface method in this case, because it is only intended to be used internally.
Here is a link to a useful blog post on this topic.

Understanding Interfaces Better

As I looked at many of the interface answers from questions here, and on Google and on this video class tutorial I am looking at I have a question. I am asking here because I can't comment if my reputation is not high so hopefully this is not to redundant. I am understanding that interfaces is like psuedocode but with more of an actual way to implement your psuedocode into the program. I undertsand
public Interface someInterface{
public void doSomething();
}
is like saying we need that function in our program so lets make this interface so when we do this
public class imDoingSomething implements someInterface{ // looking at the implements someInterface
#Override // optional
public void doSomething(){
System.out.println("Doing Something");
}
}
it makes sure as I write my program I don't forget to write this function for it is vital to my program. Is this correct?
In your example you have correctly implemented an interface. An interface can be viewed as a contract that a class must fulfill. Knowing that the class has met the requirements specified by an interface allows the object to used as the interfaces type by client code and guarantees particular methods will exist with a specified signature. This can make code more abstract and reusable for a variety of types.
So if we have an interface Playable:
public interface Play{
public void play();
}
And two classes implementing Playable:
public class Record implements Playable{
public void play(){
System.out.println("Playing Record");
}
}
public class MP3 implements Playable{
public void play(){
System.out.println("Playing MP3");
}
}
They can be used in an abstract manner by a client because it knows all classes implementing Playable have a play method:
public class Application{
List<Playable> audioFiles = new ArrayList<Playable>();
public static void main(String[] args){
audioFiles.add(new Record());
audioFiles.add(new MP3());
for(Playable p: audioFiles){
play(p);
}
}
public static void play(Playable playable){
playable.play();
}
}
On a side note
Follow Java naming standards when creating classes or interfaces. In Java these types use a capital letter for each word in the name. So your example would have a SomeInterface interface and a ImDoingSomething class.
It's more easy if you see interfaces from a consumer perspective - when you have a class which uses other objects and does not care about how these objects are concretely defined but only how these objects should behave, one creates an interface providing the methods and using it internally - and everyone which wants to use this certain class has to provide access to his data through implementing the interface so that the class knows how access everything on a code level.
An interface is a collection of abstract methods[No defination]. A class implements an interface, thereby inheriting the abstract methods of the interface.With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public.
You can not instantiate an interface - you can instantiate one of their subclasses/implementers.
Examples of such a thing are typical in the use of Java Collections.
List<String> stringList = new ArrayList<String>();
List is interface but the instance itself is an ArrayList
Interfaces are a way of enforcing design restrictions. By declaring the type of a variable or parameter as an interface, you're sure that the instance referenced by that variable or parameter is going to have an implementation for every method of the interface. That's the basis of polymorphism.

If both interface and abstract class having same methods then which one is better to override all methods into my class in java? [duplicate]

This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 9 years ago.
Hi I have faced in my SCJP examination this question. If both interface and abstract class having same methods then which one is better to override all methods into my class in java? Please explain me in different scenarios for which one is better to take.
This is interface :
interface ArithmeticMethods {
public abstract void add();
public abstract void sub();
public abstract void div();
public abstract void mul();
}
This is abstract class :
abstract ArithMethods {
public abstract void add();
public abstract void sub();
public abstract void div();
public abstract void mul();
}
This is my class name: ArithMethodImplemenation class.
Now at what scenario I should do like this
public ArithMethodImplemenation implements ArithmeticMethods{
//override all methods of ArithmeticMethods
}
or at what scenario I should do like this
public ArithMethodImplemenation extends ArithMethods{
//override all methods of ArithMethods
}
Please explain me with different scenarios. And my friends also faced this question in so many interviews. But they couldn't succeed.
There is no point in having an empty abstract class with only abstract methods.
Just use an interface instead.
Remember in Java you can extend only one class but can implement multiple interfaces.
I do not see the point of an abstract class with only abstract methods and no fields.
An abstract class is supposed to help you by implementing parts of common functionality to avoid having to rewrite that common code in implementing classes.
In that case the interface is more appropriate as it only defines the method signatures.
You should implement because inheritance primarily meant to inherit all methods from the superclass. Implementation provides a framework where you aren't overriding all your empty inherited methods.
According to the Java Programming Language, Second Edition, by Ken Arnold and James Gosling:
Inheritance - create a new class as an extension of another class, primarily for the purpose
of code reuse. That is, the derived class inherits the public methods and public data of the
base class. Java only allows a class to have one immediate base class, i.e., single class
inheritance.
Interface Inheritance - create a new class to implement the methods defined as part of an
interface for the purpose of subtyping. That is a class that implements an interface “conforms
to” (or is constrained by the type of) the interface. Java supports multiple interface inheritance.

can we use extends in place of implement to use interface

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)

Why an interface can not implement another interface?

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.

Categories

Resources