Thursday, September 26, 2013

Java : Abstract Class VS Interfaces


Abstract Class VS Interfaces

 

 


Abstract Class VS Interfaces
Inheritance :

class animal{
void eat(){System.out.print("animal eat");}
}

class dog extends animal {
}

class Test {
public static void main(String[] args){
dog d=new dog();
d.eat(); // instance dog can inherit animal property
}
}


Abstract Class :

abstract class animal{
void eat(){System.out.print("animal eat");}
abstract void noise(); // No definition
}

//dog class can inherit all properties except method declared as abstract
//Abstract method needs to be defined explicitly in the subclass ie., dog

class dog extends animal {
void noise(){System.out.print("bark");}
}

class Test {
public static void main(String[] args){
dog d=new dog();
d.eat();
d.noise();
}
}

Ref : http://www.javacoffeebreak.com/faq/faq0084.html
To summarise:
1.Use abstract classes- can inherit all methods except ones declared as abstract.Abstract method should be declared explicitly in the calling method Ex :all animals eat,sleep but make different sound(sound can be made abstract which is explicitly defined in subclass)

2.Use interfaces - here all methods are abstract by default and everything has to be implemented (once implemented gives you a skeleton on things needs to be defined )
Interface:
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.


/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}


/* File name : MammalInt.java */
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();
}
}



4) NOTE:
Using an abstract class, you can have functions, that dont need to get implemented by the classes inheriting the abstract class. (http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
Using an interface, every subclass has to define every method, provided by this interface. (http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
Use an abstract class when you want to make one or more methods not abstract.
If you want to keep all abstract, use an interface.
5) Links
http://www.javatpoint.com/abstract-class-in-java
http://www.programmerinterview.com/index.php/java-questions/interface-vs-abstract-class/

--------------------------------------------------
Uses of Interface
One reason I use interfaces is because it increases the flexibility of the code. Let's say we got a method that takes an object of class type Account as parameter, such as:

public void DoSomething(Account account) {
// Do awesome stuff here.
}

The problem with this, is that I have to send only Account object as a parameter.
Take this below example, which instead uses an account of type= Interface as parameter.

public void DoSomething(IAccount account) {
// Do awesome stuff here.
}

This solution is not fixed towards an implementation, which means that I can pass it a SavingsAccount or a JointAccount or CurrentAccount (both who has implemented the IAccount interface ie., ) and get different behavior for each implemented account.

------------------------------------------------------------------------------------------

Uses of Interface

One of the many uses I have read is where its difficult without multiple-inheritance-using-interfaces in Java :

class Animal
{
void walk() { }
....
.... //other methods and finally
void chew() { } //concentrate on this
}
Now, Imagine a case where:

class Reptile extends Animal
{
//reptile specific code here
} //not a problem here
but,

class Bird extends Animal
{
...... //other Bird specific code
} //now Birds cannot chew but Bird classes can also call chew() method which is unwanted

Better design would be:

class Animal
{
void walk() { }
....
.... //other methods
}

Animal does not have the chew() method and instead is put in an interface as :

interface Chewable {
void chew();
}

and have Reptile class implement this and not Birds (since Birds cannot chew) :

class Reptile extends Animal implements Chewable { }

and in case of Birds simply:

class Bird extends Animal { }
-------------------------------------------------------
Rules for using Abstract ,Interface ,extending a class

Java interface is like a 100% pure abstract class.You MUST implement all abstract methods
Concrete class
-normal class - when your new class doesn’t pass the IS-A test for any other type.

When To extend a class ?
-when u need to add new behaviors and Passes IS-A.

How to implement Has -A functionality in an object ?
-Instance Variable or class variable
When To Use an abstract class -
A template for a group of subclasses and you have at least some implementation code that all subclasses could use.
when you want to guarantee that nobody can make objects of that type.
Abstract class uses methods as well as abstract methods

Use an interface -

when 100% abstract and static methods is allowed
when you want to define a role that other classes can play

--------------------------------------------------------
interface tree{
production();
}

class mango implements tree{
production(){}
}

class grape implements tree{
production(){}
}

psvm[]{
tree t=new mango();
tree t=new grape();
}

now user can create a new tree type like strawberry , orange etc., which has implement tree and use --
tree t=new orange();

ref:
http://catchbug.blogspot.in/2015/06/jave-excellent-interface-example.html





13 comments:

  1. This is my favorite Java OOP Interview question for Java developers, more important for beginners.

    ReplyDelete
  2. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in java programming your post help me a lot.Thanks for your informative article.java training in chennai | chennai's no.1 java training in chennai

    ReplyDelete
  3. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more .
    java training in chennai | Best java training in chennai | java training | java training in chennai with placement

    ReplyDelete
  4. perfect explanation about java programming .its very useful.thanks for your valuable information.top 10 java training institutes in chennai | java training in velachery

    ReplyDelete

  5. Your blog is very useful for me, as your tutorial sessions are indeed of great benefit. chennai's no.1 java training in chennai | best java institute in chennai

    ReplyDelete
  6. Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
    best java training in velachery |
    java training institutes in chennai

    ReplyDelete
  7. Australia Best Tutor is one of the best Online Assignment Help providers at an affordable price. Here All Learners or Students are getting best quality assignment help with reference and styles formatting.

    Visit us for more Information

    Australia Best Tutor
    Sydney, NSW, Australia
    Call @ +61-730-407-305
    Live Chat @ https://www.australiabesttutor.com




    Our Services

    Online assignment help Australia
    my assignment help Australia
    assignment help
    help with assignment
    Online instant assignment help
    Online Assignment help Services

    ReplyDelete
  8. Best kitchen chimney installation and service in Faridabad
    When cooking with oil, you will see the fact that smoke usually receives emitted in case you often uses the identical oil. Typically, these form of eating places have today's hoods as well as exhaust fans.
    Visit here
    Kitchen Chimney Repair Service in Noida
    Kitchen Kitchen Chimney Repair Service in Vaishali
    Kitchen Kitchen Chimney Repair Service in indirapuram
    Kitchen Kitchen Chimney Repair Service in vasundhra
    Kitchen Kitchen Chimney Repair Service in faridabad

    ReplyDelete