Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Class and Interface

 
Bis Bang
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi' all
can u plz clear the concept?
If I am given two component one uses only interfaces and other uses only abstract classes.. Which should i go for and why? I am looking for an answer which signifies it at the Design and Architecture level of a project..
Thanx in advance
 
Sonu Kaush
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interfaces - These are Classes which contain only declaration.
These can be used only when you want specifc varaibles or method names to be used.
Eg : - 1) You want some constant to be used all over in code.
It can be declared in the interface.
2) Assume there is a class A that calls "calculate" method of all the the associated classes. The Class A can dynamically make the object of the Associated class and call this method.
Abstarct Classes - This call can be used to provide some reusable functionality.
1) You need a place where the connection if required for the database, We can write this method in an Abstract class and then all the inheriting classes can call this method to fetch the connection.
2) In the same class i can provide some fixed functions(select(), delete()..) which need to be overridden .
Abstarct classes can help to implement the DAO Pattern.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What we're after is "loose coupling" and closely related "information hiding", buzzwords that have been around since "modules" were invented. You want one class to know as little as possible about other classes it works with. You want to be able to change or replace one class without breaking any others. The more Class A knows about Class B, the more likely Class A will be broken by a change to Class B.
When programming to an interface like List, you know only the method signatures another object promises to implement. This is a good level of low coupling.
When extending an abstract class you are dragging along all of its code. This is very tight coupling even though you may not know much about the code in the abstract class. It would be easy for a change in the abstract class to break your concrete class.
So as a theoretical ideal, interfaces are safer. As a practical matter, abstract classes with default behavior and framework style control are often useful. Hope that made sense!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic