Abstract classes have atleast one method abstract and interfaces have all abstract methods.
If you are developing some application in which any entity can have more than one implementation, it is good practice to use an interface and implement the classes using interfaces.
If some of the functionality of an entity is already known and other methods can have different implementations, then creating an abstract class is better.
It's all a part of having a good design. Look around in the API docs and you'd find lots of abstract classes and interfaces. Try to figure out why they are so... I hope I didn't confuse you.
Read the URL for better View
http://java.sys-con.com/read/36250.htm
> > I want to know. when we have to abstract class and
> > when a interface.
>
> One way you could decide is if you need to combine
> properties from more than one. Interfaces can be
> combined classes cannot.
"Properties"? You mean methods? Yes, you can combine methods from multiple classes into one class. It's called composition and delegation.class A {
void aaa() {}
}
class B {
void bbb() {}
}
class C {
A a = new A();
B b = new B();
void aaa() { a.aaa(); }
void bbb() { b.bbb(); }
}
What you can't do is combine type from multiple classes into a single class. That is, with the above, C could have an IS-A relationship with either A or B, and could be used wherever that particular type is required, but it could not stand in place of both. It can't be (IS-A) both an A and a B.
If A and B were interfaces (or if at most one of the were a class), then we could say both C IS-A A and C IS-A B.
> Abstract classes have atleast one method abstract
Not necessarily. You can have an abstract class with no abstract methods.
> If you are developing some application in which any
> entity can have more than one implementation, it is
> good practice to use an interface and implement the
> classes using interfaces.
>
> If some of the functionality of an entity is already
> known and other methods can have different
> implementations, then creating an abstract class is
> better.
I wouldn't say one or the other is "better." They serve two different purposes, and are often used together. The interface defines the type, and the abstract class provides some common implementation. (See Colleciton, List, AbstractList, ArrayList, etc. in java.util.) But you could have other classes that implement the interface without using the abstract class for common implementation.
> > One way you could decide is if you need to combine
> > properties from more than one. Interfaces can be
> > combined classes cannot.
>
> "Properties"? You mean methods? Yes, you can combine
> methods from multiple classes into one class. It's
> called composition and delegation.[code]
Ok you are right. I must be more careful to be accurate.
(or even correct!)