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.
Related
I am little confused about abstraction in java.
I have checked many pages stating that abstraction is data hiding(Hiding the implementation).
What I understand about abstraction is it is 'partial implementation'. Just define what you are going to need in an abstract class/interface and afterwards extend/implement them and add your own functionality.
What I don't understand is how this is a data hiding? You are going to get access to the code once you implement the class/interface and you will modify it according to your need.
I have checked many questions, articles on this but still confused about this.
Any help is appreciated.
Thanks.
Maybe an example help you better. Suppose you want to implement a Graph class which may be have adjacency list or adjacency matrix to represent its nodes. So in abstract you want to "addNode" "addEdge" to this graph at least:
public abstract class Graph
{
public abstract int addNode();
public abstract void addEdge(int from, int to);
}
Now you can extend two classes:
public class GraphAdjList extends Graph
{
private Map<Integer,ArrayList<Integer>> adjListsMap;
public int addNode()
{
//list based implementation
}
public void addEdge(int from, int to)
{
//list based implementation
}
}
public class GraphAdjMatrix extends Graph
{
private int[][] adjMatrix;
public int addNode()
{
//matrix based implementation
}
public void addEdge(int from, int to)
{
//matrix based implementation
}
}
when you call either of addEdge from these two classes you don't have to worry about the data structure behind it, you just know that you get the result you needed so for example:
Graph g1,g2;
g1 = new GraphAdjList();
g2 = new GraphAdjMatrix();
g1.addEdge(1,2);
g2.addEdge(1,2);
through polymorphism you call two different functions but get the same result as client of the Graph.
Another real life example would be car brakes. As a car client, the manufacturer gives you a pedal to push without knowing what is the implementation of the brake in the back-end. It can be a drum-brake or disc-brake implementation in the back. All you need is to push the brake!
You are confusing abstraction (the programming pattern) with the abstract keyword of the Java language. Despite the similitude, they are only very lightly related semantically.
Abstraction means that you hide the implementation details from the code that uses a class or method. The code using your method does not need to know that you are implementing say, a List, using arrays or dynamic pointers or an embedded database or files in a filesystem.
abstract is used to mark classes that have methods that are only declared and not implemented. It is "abstract" in the sense that they cannot be instantiated, you cannot create any instances out of these classes (but you can create them out of their concrete subclasses).
I'm not sure if this answers your question but if you're talking about abstract classes in general, they are there to provide functionality to a child class that extends it without the child class having to know or deal with all the details of the implementation (it's hidden from the user of the child class).
Let's take a car for example:
public abstract class Vehicle {
protected int _numberOfWheels;
public Vehicle() {
this._numberOfWheels = 4;
}
}
public class Truck extends Vehicle {
public int carryingLoad;
public Truck() {
this.carryingLoad = 4000; // kg or something
}
}
So vehicle is an abstract instance of a vehicle object and already has some functionality associated with it, such as the number of wheels. It's a protected method, so if I create a new instance of truck:
// Inside main
Truck truck = new Truck();
I cannot change the number of wheels, however, if I were to write a function for truck within the class like:
// Inside the Truck class
public void addSpareTire() {
this._numberOfWheels++;
}
So that I could call it like:
// Inside main
truck.addSpareTire();
I could still interact with some variables, but only thorough the functions in the class that extends the abstract class. I can add one tire at a time by calling addSpareTire(), but I could never interact directly with _numberOfWheels from the main function where I am using the Truck object, but I can from inside the Truck class declaration. From the user of the truck object, that information is hidden.
I don't know if this is what you're asking for. Hope this helps.
In Object oriented programming Abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words user will have the information on what the object does instead of how it does it.
check the following link for more details:
http://www.visionsdeveloper.com/tutorial/java/java-abstraction.jsp
You are going to get access to the code once you implement the class/interface and you will modify it according to your need.
I guess you are little confused about the concepts which language gives you like Abstraction here. You always have access to your own code but the things like Abstraction OR Polymorphism gives you the ideal ways which things must be. So in Abstraction you are just saying I know there will be a behavior having name someThing as abstract method but right now you dont know how it will behave, The implementer will tell us how this will be. See following code.
abstract class Game{
public abstract void play();
}
class Football extends Game{
#Override
public abstract void play(){
// write how football play
}
}
class Cricket extends Game{
#Override
public abstract void play(){
// write how Cricket play
}
}
I am here leaving a question for you.
Why you are making class level attributes public/protected/private although you have access to the code when you implement?
I think you are confused about two things
Abstract concept in OOPs and its implementation in Java
abstract class in java
Abstract : There is OOPs concept called Abstract. Here, user can capture necessary features of an object. This abstract concept implemented as class and object in java. So, coming to you question, data hiding, when you capture important features of an object in the form of class those features are accessible only to their own class's object. Here, you are hiding all features of a class from outside the class/world. So, it is called as data hiding
abstract class : This is the feature of the Java implementation. If you don't know complete implementation then you can go for abstract class of java.
Hope this helps you to understand a little
Thanks
Data hiding is when you cannot understand how to work API internally (for example, ArrayList) without reading the documentation. API creators don't provide any access to the array that underlies there.
You hide API implementation from users that will be used it. They shouldn't worry about how it works internally, they are only interested in the functionality which is provided to them.
There is a good article about that.
It is not hiding the information from you, but from the client of your abstraction. Take a look at this example.
public class Demo {
Client client = new Client(new Implementation());
}
public interface Abtraction {
void doWork();
}
public class Implementation implements Abtraction{
#Override
public void doWork() {
//doingTheWork
}
}
public class Client{
private Abtraction theAbstraction;
public Client(Abstraction theAbstraction){
this.theAbstraction = theAbstraction;
}
}
The class Client is unaware of the implementation of Abstraction, this means that the Demo class can provide different implementations of Abstraction without messing up the Client.
Data Hiding is basically hiding details about internal Data Members of a class and only exclusively giving the concerned class access to it.
Thus it avoids unnecessary penetration from other classes in the application or from any other application, meaning other classes cannot access private member variables directly.
Thus in this way you abstract internal details of the concerned class.
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 know few differences between abstract class and concrete class. I know that you can't create an instance with abstract class unlike concrete class, abstract class can have 'abstract' methods.
But i have an example like the following. A lot of times, we see the following examples at work. I will just skip some common methods that can be defined in the Parent class.
public abstract class Parent {
public void init() {
doInit();
}
public abstract void doInit();
}
public class Child extends Parent {
public void doInit() {
// implementation
}
}
I think that we can do the same thing with a concrete class like the following.
public class Parent {
public void init() {
doInit();
}
public void doInit() {
// Empty
}
}
I am curious to see if there is any unique situation that we have to use abstract class. Is there any significant difference during runtime with the above example?
Thank you.
The reason to use abstract class in this situation is to force everyone inheriting your base class to override the abstract doInit method. Without the class and the method being abstract, they may forget to do so, and the compiler would not catch them.
In addition to this pragmatic purpose, abstract classes provide a powerful way to communicate your design idea to the readers of your code. An abstract class tells the reader that the methods inside provide some common implementation for a group of related classes, rather than implementing a single concept that you are modeling. Very often communicating your intent to your readers is as important as it is to write correct code, because otherwise they might break something while maintaining your code.
It is customary in Java to call abstract classes Abstract...; in your example that would be AbstractParent.
Of course you can do it that way, but it all depends on the right business logic.There might arise a situation where you'd want to enforce a policy on people extending your code.
For example, I write an Employee class and you extend my class for writing a ProjectManager class. But suppose the business does not allow direct instantiation of Employee (like I said, just an example). So I declare my Employee class as abstract, thereby enforcing upon all extenders (read:you) of my class the rule that they can't instantiate Employee directly. (It will happen indirectly through the inheritance chain, of course, i.e. parent objects are created before child objects.)
Used properly, a person at place A controls how another person at place B will code.
A concrete class is one which has implementation (code inside) for all the methods. It does not matter whether it is derived from some other class.
public abstract class IAmAbstract{
public void writeMe(){
System.out.println("I am done with writing");
}
}
public class IAmConcrete extends IAmAbstract{
public void writeMe(){
System.out.println("I am still writing");
}
}
Abstract classes have a variety of useful properties in use with software design.
Other than the obvious differences, such as being unable to be instantiated and being able to hold abstract methods. They are useful for defining common, yet overridable, functions, holding static methods that deal with it's children in a logical manner.
My favorite is the abstract factory pattern though.
By making a factory that is the parent of all the classes it may create, it can force functionality required for creation, this actually causes an odd artefact where technically tighter-coupled code is actually easier to maintain.
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.
Is it possible to have an inner class inside the interface in java ???
You can. But here's what O'Reilly says about it:
Nested Classes in Interfaces?
Java supports the concept of nested classes in interfaces. The syntax and dynamics work just like nested classes declared in a class. However, declaring a class nested inside an interface would be extremely bad programming. An interface is an abstraction of a concept, not an implementation of one. Therefore, implementation details should be left out of interfaces. Remember, just because you can cut off your hand with a saw doesn't mean that it's a particularly good idea.
That said, I could see an argument for a static utility class nested into an interface. Though why it would need to be nested into the interface instead of being a stand-alone class is completely subjective.
I agree that this should be generally rare, but I do like to use inner classes in interfaces for services when the interface method needs to return multiple pieces of information, as it's really part of the contract and not the implementation. For example:
public interface ComplexOperationService {
ComplexOperationResponse doComplexOperation( String param1, Object param2 );
public static class ComplexOperationResponse {
public int completionCode;
public String completionMessage;
public List<Object> data;
// Or use private members & getters if you like...
}
}
Obviously this could be done in a separate class as well, but to me it feels like I'm keeping the whole API defined by the interface in one spot, rather than spread out.
Yes, it is possible but it is not common practice.
interface Test
{
class Inner
{ }
}
class TestImpl implements Test
{
public static void main(String[] arg)
{
Inner inner = new Inner();
}
}
Doesn't answer your question directly, but on a related note you can also nest an interface inside another interface. This is acceptable, especially if you want to provide views. Java's collection classes do this, for example Map.java in the case of the Map.Entry view:
public interface Map<K,V> {
...
public static interface Entry<K,V> {
....
}
}
This is acceptable because you're not mixing implementation details into your interface. You're only specifying another contract.
Yes. Straight from the language spec:
An inner class is a nested class that is not explicitly or implicitly declared static.
And (boldface mine):
A nested class is any class whose declaration occurs within the body of another class or interface.
One use case for this that I find quite useful is if you have a builder that creates an instance of the Interface. If the builder is a static member of the Interface, you can create an instance like this:
DigitalObject o = new DigitalObject.Builder(content).title(name).build();
It is legal, but I only really do it with nested interfaces (as already mentioned) or nested enums. For example:
public interface MyInterface {
public enum Type { ONE, TWO, THREE }
public Type getType();
public enum Status { GOOD, BAD, UNKNOWN }
public Status getStatus();
}