why is the requirement of interface?
Hi ,
I am not new to java and had worked on the server side
java.After one year of my experience I feel there is
lots and lots to learn in java.Now I am concentrating
mostly on the concepts of Object oriented programming. In java I can under stand the use of class.
But once there is the interface in discussion I dont
understand clearly why we require it.In some sources
they had mentioned the loading of interface requires
less allocation.I would like to know the object level
explaination of interface,abstract class and many more.
Hope I get the appropriate answer and would like to
explaination from java gurus.
regards vicky
[731 byte] By [
vickyk] at [2007-9-26 14:17:57]

Interfaces are required to support some degree of multiple inheritance. This is because a class can implement several interfaces, but extend only one class.
>object level explaination of interface,abstract class and many more
An interface declares behaviour.
An abstract class defines data and declares behaviour and can define behaviour
A class defines data and defines behaviour.
The easiest way that I have come up to describe a theorectical model is the following.
-Interface is the most abstract.
-Next is "abstract class". An interface can be the parent of an "abstract class" but the reverse is not true.
-A class is the least abstract. It can have either (or both) an interface or "abstract class" as a parent. The reverse is not true.
Hi,
The concept of multiple inheritance by using the interface is ok,but it doesnot give
the help in understanding the how the interface will behave in jvm.Consider the
interface MyInterface being implemented by MyClass.It will be something like this:
1) interface MyInterface
{
public abstract void method1();
}
2) public class MyClass extends SecondClass implements MyInterface
{
public void method1()
{
//implementation for MyClass
}
}
3)Considering the MyClass.class being formed,Also MyInterface.class
being created .
4) once the jvm loads MyClass.class and MyInterface.class.Here for this implementa
tion two objects are being loaded in mem(allocations for two objects).
5) if I write this
public class MyClass extends SecondClass
{
public void method1()
{
//implementation for MyClass
}
}
I can use the method1() directly,Hence only one object will do my job,less mem allocation .
6) java provides us lot of interfaces the implementation is being handled by them.
Please give me the details of memory allocations level explaination for the interfaces and abstract classes.
regards vickyk
Turn to any beginning Java book for a far more thorough explanation of interfaces than you could ever get in a forum...
Hi, I have reffered lots of beginners book and documentation but I could not find the object/memory level explaination.If you have some reference do mail me. regards vickyk
What do you mean by the object/memory level explanation? Perhaps if you learn the bytecode you'll understand better. Programming for the Java Virtual Machine is the best tutorial on the subject that I've seen. However, be aware that each different JVM will have a different implementation of interfaces and classes, so implementation details are not discussed.
Hi,
Considering the interface myInterface and class myClass having the same methods to be precise
the similar methods within it.Then once the jvm loads
both of them which will allocate lesser space?
Also what does the public abstract interface Statement mean.Is it a abstract class or a interface?Many more classes are of this type in java.What
is the state of the methods in it whether they r abstract
or implemented,hope u get what i require
thanks
vickyk
OK, I'll give it a try.
An interface defines only access interfaces for classes which have to implement it.
As there is no implementation, the interface is considered abstract by definition.
A class implementing it, by defining
class A implements myInterface
{
}
*must* implement all interface methods or it has to be declared abstract.
Being abstract means, that this class can not be instantiated itself but has to be extended by child classes which then must the interface themselves.
You can even declare classes being abstract without using interfaces to enforce the programmer to extend it with different behavior.
Think about a class called car, which has some attributes: 4 wheels, a steering wheel, and engine, including the methods drive(), break() and steer().
The class itself does not specify a specific type of car exactly, like a sports car, or a truck.
So the car class should not instantiated, as a result we declare it abstract.
We can now derive the subclasses Truck, SportsCar and RacingCar with some more and class specific attributes.
public abstract class Car
{
Wheels carWheels=new Wheels[4];
SteeringWheel sw;
Engine carEngine;
public void drive()
{
...
}
publicvoid break()
{
...
}
public void steer()
{
...
}
}
public class Truck exteds Car
{
Radio myRadio;
public void transmitRadioMessage();
public void drive()
{
...//implementation
}
publicvoid break()
{
...//implementation
}
public void steer()
{
...//implementation
}
}
and so on.
The Truck class is still accessible via its Car parent:
Car newCar=new Truck();
newCar.drive();
Toa void having to provide generic implementations of drive, break and steer in the Car class, we can define an interface CarInterface:
public interface CarInterface
{
public void drive();
public void break();
public void stear();
}
and let Car implement the interface:
public abstract class Car implements CarInterface
{
Wheels carWheels=new Wheels[4];
SteeringWheel sw;
Engine carEngine;
}
As one can see, the methods drive, break and steer are now missing in the declaration and *must* be provided by the classes Truck, SportsCar and RacingCar derived from the abstract car, or they are considered being abstract themselves.
This way, we have created a generic interface to the client classes, as they can also be accessed through the CarInterface and the methods declared ther can be applied:
CarInterface ci=new Truck();
ci.drive();
ci=new SportsCar();
ci.break();
etc.
This has nothing to do with memory considerations, it is just using an abstraction layer for declaring generic data interfaces and to enforce the programmer to stay on a defined path.
But if you are refering to memory, if the JVM loads the interface, it will propably require less space.
But using it requires the objects class fully loaded so both are staying in memory:
CarInterface ci;//Loads CarInterface.class
ci=new Truck()//Loads Truck.class
//additionally, as it ha to
//allocate the appropriate
//space on the heap
I hope this helps.
Oliver
ofels at 2007-7-2 15:52:31 >

hi oliver,
Well the explaination was great and the part specifying
the loading of CarInterface and Truck was well explained(Which i expected). Now my question is:
1) Once you define the line:
CarInterface ci;
Does it loads the CarInterface.class file in the JVM
or it creates just the reference at the STACK memory.
As for the normal classes once you define
myClass my; It does not load the myClass but the
following additional syntax does it:
myClass my=new myClass();Correct me If I am wrong?
2) As you had mentioned that the interface requires less
space that the class.
So if this part :
CarInterface ci; //Loads CarInterface.class
ci=new Truck() //Loads Truck.class
is replaced by this part
Truck t;//create a datatype
t=new Truck();//Loads Truck Class
there will be more MEMORY ALLOCATION.
Here I had modified your Truck to:
public class Truck //(removed part from your code)exteds Car
{
Radio myRadio;
public void transmitRadioMessage();
public void drive()
{
...//implementation
}
public void break()
{
...//implementation
}
public void steer()
{
...//implementation
}
}
Is not the addition code being removed(Interface)?Does
it mean the additional work of writing the interface lets
the memory allocation less?
3)
If the interface can help me why do we require
then abstract classes?
4)
a) CarInterface ci=new Truck();
b) ci.drive();
c) ci=new SportsCar();
d) ci.break();
In the above part lots of things are reflected.
in the above case
In a the ci is referenced to the Truck
In b then you are assessing the Truck object via car
interface.
Once the work with Truck is done you are using the
SpotrsCar object wth the same allocation ci in stack.
So in the above implementation three object space isbeing used.
But without interfaces:
Four allocations would be interacting(tr/sc instead of ci)
Truck tr=new Truck();
tr.drive();
SportsCar sc=new SportsCar();
sc.break();
regards vicky
is:
> 1) Once you define the line:
> CarInterface ci;
> Does it loads the CarInterface.class file in the
> he JVM
> or it creates just the reference at the STACK
> CK memory.
Classes are loaded when they are firstly referenced by an already running class object.
I have just reread this point, just to be sure.
So the same applies to interfaces.
> 2) As you had mentioned that the interface requires
> less
> space that the class.
> So if this part :
> CarInterface ci; //Loads CarInterface.class
> ci=new Truck() //Loads Truck.class
> is replaced by this part
> Truck t;//create a datatype
> t=new Truck();//Loads Truck Class
> there will be more MEMORY ALLOCATION.
When you create the datatype
Truck t;
the class is loaded and the appropriate interfaces and parents are loaded.
Memory consumption shouid be the same, it might be spread over your code if declaration and instantiation are separated (eg with lazy instation).
> Is not the addition code being
> removed(Interface)?Does
I am not sure what you are refering to.
The interface does not hold any implementation, only the declaration so nothing is removed.
In the example, methods from parent classes have been overwritten (overloaded) which however still exist in the parent.
> it mean the additional work of writing the interface
> lets
> the memory allocation less?
No, not if I understand what you are rfering to.
> 3)
> If the interface can help me why do we require
> then abstract classes?
Interfaces declare a behavior, but have no state.
Abstract classes eventually declare a basic behavior *and* can have a state(attributes).
So abstract classes are useful for general classes with a minimum set of identity which share all children in common but which is not enough to work correctly.
> 4)
> a) CarInterface ci=new Truck();
> b) ci.drive();
> c) ci=new SportsCar();
> d) ci.break();
> In the above part lots of things are reflected.
> in the above case
> In a the ci is referenced to the Truck
> In b then you are assessing the Truck object via car
> r
> interface.
> Once the work with Truck is done you are using the
> SpotrsCar object wth the same allocation ci in
> in stack.
> So in the above implementation three object
> space ace isbeing used.
> But without interfaces:
> Four allocations would be interacting(tr/sc instead
> ad of ci)
> Truck tr=new Truck();
> tr.drive();
> SportsCar sc=new SportsCar();
> sc.break();
Yes, but you can not access the transparently,
Think about a blind man who only knows about the interface: break, drive, steer but can not see what he is sitting in.
So he only accesses the methods on an object he knows how to interact with, the remaining parts are of no interest.
This is called virtual access as only the interface to an object is known- the implementation is of no interest.
BTW, thinking about JAVA programming as a matter of memory allocation issues can somehow complicate things. IMHO, memory allocation is not an important issue in JAVA.
Oliver
ofels at 2007-7-2 15:52:31 >

Memory space to load a class (abstract or not) and interfaces is not relevant.
Instances NOT classes/interfaces take up the vast majority of room.
If you have so many classes that memory used by loading them becomes a problem then in all likelyhood something is seriously wrong with your design.
> > 2) As you had mentioned that the interface requires
> > less
> > space that the class.
> > So if this part :
> > CarInterface ci; //Loads CarInterface.class
> > ci=new Truck() //Loads Truck.class
> > is replaced by this part
> > Truck t;//create a datatype
> > t=new Truck();//Loads Truck Class
> > there will be more MEMORY ALLOCATION.
> When you create the datatype
> Truck t;
> the class is loaded and the appropriate interfaces and parents are loaded.
> Memory consumption shouid be the same, it might be spread over your code if
> declaration and instantiation are separated (eg with lazy instation).
To make it clearer.
// Loads the interface. This takes memory.
// Creates a reference 'spot'. Technically takes memory
//but not in the context of this discussion.
CarInterface ci;
.
// Loads the Truck class. This takes memory.
// Presumably Truck implements CarInteface but it is already
//loaded in the previous line.
// Creates an instance of Truck. This takes memory.
// Creates a real reference. This takes memory, but it
//shouldn't matter to you, EVERY object instance takes the same
//amount. Since you can't do anything without objects
//it doesn't matter.
ci = new Truck();
.
.
// Loads the Truck class. This takes memory.
// Presumably Truck implements CarInteface so it loads that too
///and that takes memory.
// Creates a reference 'spot'. Technically takes memory
//but not in the context of this discussion.
Truck t;
.
// Truck class is already loaded.
// Creates an instance of Truck. This takes memory.
// Creates a real reference. This takes memory, but it
//shouldn't matter to you, EVERY object instance takes the same
//amount. Since you can't do anything without objects
//it doesn't matter.
t=new Truck();//Loads Truck Class
// This takes EXACTLY the same memory as the first case,
// presuming Truck is exactly the same as the first Truck.
.
Vicky,
I think you're getting confused about the purpose of the interface feature in Java. There is a functional need for it in the language to cope with limitations imposed by Java's strong typing, but generally speaking it's purpose is not functional but declarative. It's useful to think in terms of interfaces even with a language that does not require them(like Smalltalk, for which variables are untyped).
To really learn about the purpose of interfaces, you should not be thinking about memory issues or class loading or even Java - you should be thinking about OO design.
Very likely the best answer to your question, that would avoid confusing you with Java issues, could be found in a book on general OO design.
But if you study the Collections framework in java.util, you will see a very good example of the power of interfaces(preferably using a book that illustrates the class and interface heirarchies). There you will find a class heirarchy under AbstractCollection that includes implementations of ArrayList and LinkedList that are very different from each other. But conceptually they could to a large extent be treated the same way by your application, and this commonality between the two is described by the interface List, which is implemented by both classes.
So in your application, if you declare variables as type List instead of ArrayList (thereby constraining you from using some of the ArrayList-specific protocol), then you could place in it instances of either ArrayList or LinkedList, improving the flexibility of your code.
Now, for example, if you have used a LinkedList in your code(held in a variable declared as List), and later find that you are using it only as a stack in which you are removing items in the reverse order from that in which you put them in, then you will find that you could easily replace your linked list with an instance of ArrayList instead and probably get better performance. You wouldn't have to change any of the variable declarations that might be scattered throughout your code - instead only changing the code that created your original instance. In fact, you could even create your own class that implements List completely differently, and yet even existing code developed by other people who use List could use your implementation as easily as any other. My point is that the use of an interface makes your code much more flexible and adaptible.
So in reminder: the purpose of an interface has very little to do with Java the language, and is primarily an issue of good OO design that enables effective code flexibility and reuse in a clearly defined manner.
I hope this clears up a few things for you!
Cheers,
Ian
hi,
Lots of variety comimg up.Let me keep the memory
part aside for the time and work plainly.
While referring to the thinking in java I found the
author referring the polymorphism issue being handled
by the interaface.Still lots of questions do crop up in
mind,and I think lots among us will have same.
For me writing the code is not the big deal ,but to
know how the objects defined in a code behave
at run time maters.Exactly how the code tackels
the objects.
In java everything is in terms of an object,and code
what we create gives just the output of objectinteraction.
let us go back to inteface concept(keeping memory away);
class a1.1 //FIRST VERSION UTILITY
{
public void firstutility()
{
//code what I am providing in first version
}
}
class a1.2 extends a1.1
{
public void firstutility()
{
//code what I am providing in second version
}
public void secondutility()
{
//additional functionality in second version
}
}
Simalarly I can keep on going for a1.3,a1.4 etc
AN ALTERNATIVE WOULD BE
interface myUtility
{
public void firstutility();
}
class a1.1 implements myUtility
{
public void firstutility()
{
//code what I am providing in first version
}
}
For this to incorporate the next version I have
to modify the myUtility to
interface myUtility
{
public void firstutility();
public void secondutility();
}
class a1.2 implements myUtility
{
//implementation goes here
}
In the alternate(interface included) case every time
the interface has to be modified and the old version
gets discarded(Is this depreceated),so all the time
newer files.
But for the first case just including just the
additional utility.
Now explain me which you recommend and why?
thanks
Vicky,
one of the advantages of interface is forgetting about how things behave at runtime.
Using interfacing is a polymorphism concept which is designed to hide the implementation details in favor of a unique access interface.
Imagine a team of developers working on the same project.
As a projects designer it would be useful to design the interface, giving that to your developers and thus providing a common interface for the components.to interact with.
Each of those components is now accessible via this interface regardless its real implementation nature.
Its up to the developers to implement the real functionality, but they are free in the way to it. The only assumption that has to be made is how the components interact with each others defined by the interface.
If those components are now stored somewhere in a common generic storage, each can be accessed by calling the interface methods regardless its real type. This is type safety, as you dont have to make assumptions about its real type.
The question when use interfaces or which is better is a design question and depends on the purpose.
If lots of common components (objects) of different types are used and have to be accessed generically interfaces are a good idea. Here again, think about a car parking.
Lots of different car types are driven in.
For the guy driving them to the parking slots it does not matter which type it is.
He only has to know about the interface: drive(), steer(), break().
A well designed interface is the key to several technical algorithms, as there are plugin mechanisms or event handlers (eg. the ActionListener concept in Java AWT).
In most cases, an interface is designed once and should not be touched during the development process, as this indeed makes changes necessary for the implementing classes.
In your example a general statement about which approach is better can not be made,
It depends on the purpose the code is designed for.
Just as a side note, it is not a good idea starting with coding when developing a large object oriented development project. This is the hard way.
Design should always be the first step in which those issues are addressed. If you would like to get more ideas about designing object oriented solutions I can suggest some more literature.
I hope this helps.
Oliver
ofels at 2007-7-2 15:52:31 >

Vicky,
In the example you give, there is no apparent reason to use interfaces. As you point out, all you are doing is forcing yourself to maintain additional files. And as Oliver points out, it depends very much on how you would use them.
There is only one way that interfaces affect the behaviour of your code at runtime, and that is in verifying types, particularly when using dynamically loaded classes. In simple programs you can consider that all the work of interfaces takes place at compile time - where interfaces are a way of grouping behaviour and of declaring types.
Eckel tries to illustrate it in Thinking in Java(2nd Ed.) on p355, but with only one implementing class you don't get to see the advantages of using the interfaces.
Essentially, an interface is a way of grouping behaviour that belongs together, but which may be implemented differently by different classes - quite likely as only part of the behaviour for those classes. Without the help of diagrams and probably even face to face interaction, I find it very hard to explain it all. It's probably even harder for you having to do it all in english.
More than anything else, I would recommend that you try to find someone locally who know and understands OO design well (preferably several years experience, to avoid risk of confusion) and with a whiteboard or paper handy. As Oliver pointed out, the whole point of interfaces is being able to separate the concept(interface) from the implementation.
It's not easy to learn how to use interfaces effectively. Your best best is working with others who do and enjoy the "Aha!" when you finally understand. In the meantime, it would really help to look at the example I pointed out previously of java.util.List. There is a diagram on p460 of Thinking in Java that might help, along with some good explanation.
Good luck. Maybe you'll feel better if I tell you that it took me years to learn how to do OO design well, and after a dozen years I'm still learning. Once you understand the basics very well, I highly recommend Design Patterns by Gamma et al. Other books are available that take these same concepts and apply them specifically to Java(Patterns in Java series).
Cheers, Ian
Additional note: deprecation is a means by which obsolete members of a class or interface are marked as being obsolete. For example, older versions of java provided the Thread method suspend(). Sun later realized that it is a flawed feature of threads, but they couldn't just delete it from the Thread class because lots of earlier Java programs will have used it. So instead Sun declared it "deprecated" in the documentation so that developers know that they shouldn't use it, and that they can expect that future versions of Java will eventually no longer support it.
Deprecation is a javadoc feature that is used when maintaining APIs. You do not need to use it for your applications, other than to be aware that you shouldn't use deprecated methods of any APIs that you use.
Hi igraham,
After going through your prompt replies and from
various sources I could under stand one thing that
the interfaces helps in faster verification of methods
at Run time which even you has mentioned.I will give
you a case:
class a
{
method1()
}
class b extends a
{
method2()
}
class c extends b
{
method3()
}
So with the time the OBJECT keeps on modifying,and
if I am using the final object c here in my coding as:
p s v m(String ar[])
{
c cc=new c();
c.method1();
}
The flow of main goes like this:
1)At first line allocation of a,b and then c is done.
2) At the second line the jvm will check for the validitaion(Is this mean your verifying types),so here
it will have to first check the method in c(not present there) ,b(not there) and will finally gets there.The checking in c and b consumes the time at run time.
If I use the following implementation:
interface myinterface
{
// all three methods defined here
}
class c implements myinterface
{
//implementing all three
}
An my main will remain same as below:
p s v m(String ar[])
{
c cc=new c();
c.method1();
}
Now here the flow goes like this:
1) At first the c and myinterface is loaded (allocated)
2)Now checking(verification run time ) is done with
interface which will be veryfast.
Is that what interface can do?
Will be the flow in interface implemented class
be faster?
vickyk
Vicky,
I am afraid but I think that you are now totally moving into the wrong direction.
To say it once more: We are not talking about access times or memory allocation issues.
We are on a level which is more abstract than just dealing with runtime details.
Interfaces are a concept heavily tied to the object orientation not to runtime specific issues.
Interfaces define a way how classes and their objects interact.
If you are trying to fully understand the concept, do yourself a favor, simply forget about memory allocation and verification speed and reread our posts. You will notice that everything is much easier if seen from a higher level.
Oliver
ofels at 2007-7-2 15:52:32 >

>There is only one way that interfaces affect the behaviour
>of your code at runtime, and that is in verifying types,
That depends on what level you are talking about. In the implementation level, resolving a method call via a interface call is more complicated than a normal method call and so slower.
Vicky,
> After going through your prompt replies and from
> various sources I could under stand one thing that
> the interfaces helps in faster verification of
> methods at Run time which even you has mentioned.
Not really - I said that interfaces help with type verification at run-time, and as jschell points out, that type-checking takes extra time. But this issue distracts from Oliver's point that if you are trying to understand interfaces, then you are thinking in the wrong direction.
The reason for having interfaces does not lie in what goes on at runtime. The reason lies in being able to develop an application that models the real world effectively with its various classes and interfaces.
One final example I can give is the Runnable interface. Without it, every object that wanted to do thing's actively in another thread would have to be a subclass of Thread. But by having some other class implement Runnable you can run() objects of your own class. Functionally it really makes no difference, but from a conceptual perspective, having the run() method in your class may well make more sense.
>I will give
> you a case:
> class a
> {
> method1()
> }
> class b extends a
> {
> method2()
> }
> class c extends b
> {
> method3()
> }
>
> So with the time the OBJECT keeps on modifying,and
Modifying with time? The purpose of subclassing is not simply to create new versions of classes over time. As with interfaces, subclassing is generally a modelling issue, not a development-cycle issue.
> if I am using the final object c here in my coding
> as:
> p s v m(String ar[])
> {
> c cc=new c();
> c.method1();
> }
> The flow of main goes like this:
> 1)At first line allocation of a,b and then c is
> is done.
> 2) At the second line the jvm will check for the
> he validitaion(Is this mean your verifying types),so
> here
> it will have to first check the method in c(not
> ot present there) ,b(not there) and will finally gets
> there.The checking in c and b consumes the time at run
> time.
No. In fact it's in the first line, when you do the assignment, that type checking would take place. What I'm not sure of is whether in this case the compiler can produce code that doesn't type-check, since it knows for sure that your type is valid. But to you as an application programmer it makes no difference.
The second line consists of a message(function) dispatch - not a type-check. How that's implemented can vary between different VMs, but as you say, the basic idea is that the VM goes up the hierarchy until it finds an implementation of method1. I'm not a VM person at all, but my belief is that no commercial VM implementations are slower at message-dispatch just because a method is implemented far up the hierarchy.
> If I use the following implementation:
> interface myinterface
> {
> // all three methods defined here
> }
> class c implements myinterface
> {
> //implementing all three
> }
> An my main will remain same as below:
> p s v m(String ar[])
> {
> c cc=new c();
> c.method1();
> }
> Now here the flow goes like this:
> 1) At first the c and myinterface is loaded
> (allocated)
> 2)Now checking(verification run time ) is done with
> interface which will be veryfast.
> Is that what interface can do?
> Will be the flow in interface implemented class
> be faster?
Now I would like to quote Joshua Block, from page 162 of his excellent book Effective Java Programming Language Guide: "Strive to write good programs rather than fast ones." Block further quotes Knuth: "Premature optimization is the root of all evil."
I don't know of any reason for either to be faster. Unless you are implementing a VM you shouldn't care.
To REALLY understand how to use subclassing and interfaces, I think you need to take a course in OO design.
Again, good luck,
Ian
P.S. When you include code samples, put them inside blocks like this below(except you must use "[" and "]" instead of "(" and ")". All the bold and pretty colouring is done automatically - try Preview before you Post.
(code)
class MySampleCode {
// whatever
}
(/code)
hi,
Let me review the support I got from you all
SCAPEL SAYS:
1)Helps in multiple inheritance.
2)Turn to basic
3)Refer to JVM tutorial
JSCHELL SAYS:
1)Gave the fundamental definition
OLIVER SAYS:
1) Gave an explainatory answer but also specified:
--This has nothing to do with memory considerations, it is just using an abstraction layer for declaring generic data interfaces and to enforce the programmer to stay on a defined path.--
2) In most cases, an interface is designed once and should not be touched during the development process.
igraham:
1)says you get to some one who knows oops well
And then to my 16th reply:
Oliver suggests I am moving to wrong side ,jschell says verification
from the interfaces takes more time
igraham says:
--
Not really - I said that interfaces help with type verification at run-time, and as jschell points out, that type-checking takes extra time. But this issue distracts from Oliver's point that if you are trying to understand interfaces, then you are thinking in the wrong direction.
The reason for having interfaces does not lie in what goes on at runtime. The reason lies in being able to develop an application that models the real world effectively with its various classes and interfaces.
--
Now here it seeems oliver and igrahem moving in opposite direction.
According to my understading and the resources which i reffered
says the interfaces are required for type verification which is done
at run time(Late binding in java) except you define the method as
final.The concepts are being deviated as we progress,any i hope
this query will clear the concepts with time.
thanks vicky
Vicky,
> Now here it seeems oliver and igrahem moving in
> n opposite direction.
Not really ;-)
> According to my understading and the resources
> es which i reffered
> says the interfaces are required for type
> e verification which is done
> at run time(Late binding in java) except you define
> e the method as final.
This is correct. But this does not only apply for interfaces.
Type checking is done for all sorts of data objects.
But interfaces are not a requirement for type safety.
You can developer type safe software without using interfaces.
Again, interfaces can serve several purposes:
- supporting a generic way of storing data
- defining a common interaction schemes of classes and objects for developers
- emulate multiple inheritance (as it is no true mi like it was in C++ applied to classes)
- support type safety
Summarizing the points above, interfaces are a technique for designing (not implementing) object oriented, generic, type safe and reusable code.
Of course as you mentioned interfaces affect certain operations at runtime, this is of course necessary. But classes do also.
It must be completely clear, that interfaces are a software design issue, not coding .
Think about interfaces as defining a framework for the programmers later.
And dont get confused about the above postings.
They were right, the difficulty is, that everyone contributed only a small part of the whole truth, including myself.
I know it is difficult to explain concepts here over a long distance, so you should look for someone who can explain it face to face- I'd suggested myself, but there is way too much distance :-)
Oliver
ofels at 2007-7-2 15:52:32 >

Actually, Vicky, I think Oliver and I agree very much on the following points:
1) When you are thinking about memory, speed, and VM issues you are thinking in the wrong direction.
2) The real importance of interfaces is in conceptual issues of OO modeling.
And schapel and I certainly agree now(I was more optimistic than he earlier, but he's got more experience at helping people out in the forums), that you are not going to find your answer here. Abstract concepts are difficult to explain with mere text - even Thinking in Java with all of its diagrams and code illustrations hasn't explained it so that you could just read it and learn it. And it probably doesn't help that we are all coming from different directions in trying to explain it.
> According to my understading and the resources
> es which i reffered
> says the interfaces are required for type
> e verification which is done
> at run time(Late binding in java)...
Yes interfaces are used for type checking. But how much of that is happening at compile time and how much at runtime isn't important to you as an application developer. Far more important is understanding OO design.
> except you define
> e the method as
> final.
I don't understand what you are thinking here. Declaring a method as final has nothing to do with interfaces.
> The concepts are being deviated as we
> e progress,any i hope
> this query will clear the concepts with time.
> thanks vicky
I really wish I knew a good introductory OO book for helping you get the feel of what interfaces are all about.
But in Core Java 2 - Volume I there is a very good set of example on pages 226-231. First they give you an example without interfaces, and then they give a similar example that requires an interface to solve the problem effectively. I think it's better explained than in Thinking in Java.
Best of luck,
Ian
> > Now here it seeems oliver and igrahem moving in
> > n opposite direction.
>
> Not really ;-)
:)
I was too preoccupied with writing my response to notice that you were already there!
I'm exhausted. Where I am it's 2am and I just spent 45 minutes trying to figure out how to say something and then ended up saying almost nothing.
'nite all,
Ian
igraham said
>Not really - I said that interfaces help with type verification
>at run-time, and as jschell points out, that type-checking
>takes extra time.
No, you said that type checking is the reason. I am not sure where type checking applies except when the class is loaded. Type checking occurs elsewhere but it does so for classes too and so that is not relevant.
However, when a interface method is called it takes longer than other 'virtual' methods. Once again this is not due to type checking. Instead it is due to the complexity of resolving the correct method to call.
But just to make it clear, since this discussion is mostly about when one should use interfaces, a discussion of the performance characteristics should not brought in. One can not balance the tradeoffs in design/performance unless one actually understands the design aspects. And if the usage of interfaces is not understood then the design aspects are not understood.
jschell said
> igraham said
>
> >Not really - I said that interfaces help with type
> verification
> >at run-time, and as jschell points out, that
> type-checking
> >takes extra time.
>
> No, you said that type checking is the reason. I am
> not sure where type checking applies except when the
> class is loaded. Type checking occurs elsewhere but
> it does so for classes too and so that is not
> relevant.
Java's strong typing IS the reason interfaces are necessary in Java. But I was trying to say that the purpose is more to do with OO modeling.
I'm not at all knowledgeable about implementing VMs, though, and I didn't know that resolving a message-send(method call) for an interface had any extra complication - interesting.
I wasn't saying that the type-checking was any more expensive for an interface than for a class, or that the issue was relevant at all. I thought I was saying quite clearly that none of it was relevant - hence the ease with which I missed the essence of your point about resolving interface message-sends.
> But just to make it clear, since this discussion is
> mostly about when one should use interfaces, a
> discussion of the performance characteristics should
> not brought in.
Actually, it was you who brought up performance in the discussion. And I find I've learned something interesting from it, however irrelevant it is to helping Vicky understand the "why" of interfaces.
Just out of curiousity - any idea how much slower resolving a message-send is through an interface? In Smalltalk every message-send must have that same complexity - does that mean that sending a message directly to a class in Java is generally faster than message-sending in Smalltalk?
>..any idea how much slower resolving a message-send is through an interface? Small enough that I doubt that it will ever matter to me.
> >..any idea how much slower resolving a message-send> is through an interface?> > Small enough that I doubt that it will ever matter to> me.Except to point out my neglect of it in the first place :)Ian
igraham, you really give yourself away as a true smalltalk person with the "message-send" term.. in java it's "method call", but I'm sure you already know that!
jschell, interesting.. about your claim regarding a method call via an interface reference being slower than via a class reference. How is that? More specifically, exactly what do you mean by that?
I may be misunderstanding your point of view, but I don't believe it matters, internally. In other words the vm directs both calls through the same v-table and each reference points to the same reference table... as much as I recall.. and I'm not recalling very well these days!
> igraham, you really give yourself away as a true
> smalltalk person with the "message-send" term.. in
> java it's "method call", but I'm sure you already know
> that!
Lol! Actually, I think OO purists would tell you otherwise. I think what happened is that many many developers came en masse to the world of Java being either new to OO or having migrated awkwardly through C++. The furthest they could get in their adaption to the new vocabularly was to use the word "method" instead of "function". But we all know that language is driven by cultural usage. Even Oxford reneged on their disapproval of split infinitives.
Did you know that Oxford also legalized "they" as the accepted genderless singular pronoun? As in, the user should click here, and then they should click there. So you don't have to say "she" or "he/she" and embarrass the reader.
Somebody changed the interface :)
> jschell, interesting.. about your claim regarding a
> method call via an interface reference being slower
> than via a class reference. How is that? More
> specifically, exactly what do you mean by that?
>
> I may be misunderstanding your point of view, but I
> don't believe it matters, internally. In other words
> the vm directs both calls through the same v-table and
> each reference points to the same reference table...
> as much as I recall.. and I'm not recalling very well
> these days!
I think jschell knows his stuff - but I gotta admit that I too retain a little skepticism. I'm glad I'm not alone.
Ian
>How is that? More specifically, exactly what do you mean by that?
A normal virtual method call is basically fixed.
Because there can be more than one interface it requires some indexing to make sure the right vtable pointer is used. A similar problem exists in C++ when resolving vtable indexing with multiple inheritence.
I could be mistaken but I believe "Inside the Virtual Machine 2nd edition" discusses it in more detail along with examples.
I understand your reasoning now. But I still don't believe a method call via interface reference is slower than via class reference. e.g.,
interface IFoo
{
public void foo();
}
class Foo implements IFoo
{
public void foo() {}
}
class Bar extends Foo
{
public void foo() {}
}
Bar bar = new Bar();
bar.foo();
Foo foo = (Foo)bar;
foo.foo();
IFoo ifoo = (IFoo)bar;
ifoo.foo();
I could be wrong, but I believe all method calls are equally efficient because the v-tables for each reference are determined at the times of each cast (not during the method call).
Call me cooky, but as I understand it a vtable is determined at the time the reference is assigned and not during a method call. That is why I believe that a method call from an interface ref is equally efficient as from a class reference.
Ok, my browser must have dual personalities.
Naturally the only way to resolve it is to time it. I ran the following, compiling with jikes and running with java from 1.3.1. It gave fairly consist results with the interface method being about 10% slower.
interface II
{
void doit1();
}
public class TTest implements II
{
static public void main(String argv[])
{
testDirect();
testIndirect();
}
public void doit1()
{
}
public void doit2()
{
}
final private static long loopCount = 1000000000;
static void testDirect()
{
TTest t = new TTest();
// Make sure everything is resolved.
t.doit2();
// time it.
long start = System.currentTimeMillis();
for (int i=0; i < loopCount; i++)
t.doit2();
long stop = System.currentTimeMillis();
System.out.println("direct = " + (stop - start));
}
static void testIndirect()
{
TTest t = new TTest();
// Make sure everything is resolved.
t.doit1();
// time it.
long start = System.currentTimeMillis();
for (long i=0; i < loopCount; i++)
t.doit1();
long stop = System.currentTimeMillis();
System.out.println("indirect = " + (stop - start));
}
}
Hmmm...
First, I presumed you were comparing like method calls from differently typed references i.e., II.doit1() vs. TTest.doit1(). the fact that II is an interface and not a class has no bearing on the issue -- the method calls are equally efficient.
Second, I'm not sure your benchmark is very trustworthy the way you are executing it -- not that you are at fault. I changed it a smidge so that it is exercised more and, therefore, produces more meaningful results. The results follow. And as you can see they are very much equal.s:>\java\jdk1.3\bin\java TTest2
direct = 5999
indirect = 5999
direct = 5988
indirect = 5989
direct = 5989
indirect = 5988
// Following is the slightly changed test. Note I only changed main() to execute the test in three batches.
interface II3
{
void doit1();
}
public class TTest2 implements II3
{
static public void main(String argv[])
{
testDirect();
testIndirect();
testDirect();
testIndirect();
testDirect();
testIndirect();
}
public void doit1()
{ }
public void doit2()
{ }
final private static long loopCount = 1000000000;
static void testDirect()
{
TTest t = new TTest();// Make sure everything is resolved.
t.doit2();// time it.
long start = System.currentTimeMillis();
for (int i=0; i < loopCount; i++)
t.doit2();
long stop = System.currentTimeMillis();
System.out.println("direct = " + (stop - start));
}
static void testIndirect()
{
TTest t = new TTest();// Make sure everything is resolved.
t.doit1();// time it.
long start = System.currentTimeMillis();
for (int i=0; i < loopCount; i++)
t.doit1();
long stop = System.currentTimeMillis();
System.out.println("indirect = " + (stop - start));
}
}
I knew I should have looked at the byte codes. The previous code resolves directly to the methods. The following invokes the methods correctly.
Results:
direct = 2073
indirect = 2644
direct = 1932
indirect = 2604
direct = 1893
indirect = 2574
.
.
interface II
{
void doit1();
}
public class TTest implements II
{
static public void main(String argv[])
{
TTest t = new TTest();
testDirect(t);
testIndirect(t);
testDirect(t);
testIndirect(t);
testDirect(t);
testIndirect(t);
}
public void doit1()
{
}
public void doit2()
{
}
final private static long loopCount = 100000000;
static void testDirect(TTest t)
{
// Make sure everything is resolved.
t.doit2();
// time it.
long start = System.currentTimeMillis();
for (int i=0; i < loopCount; i++)
t.doit2();
long stop = System.currentTimeMillis();
System.out.println("direct = " + (stop - start));
}
static void testIndirect(II t)
{
// Make sure everything is resolved.
t.doit1();
// time it.
long start = System.currentTimeMillis();
for (long i=0; i < loopCount; i++)
t.doit1();
long stop = System.currentTimeMillis();
System.out.println("indirect = " + (stop - start));
}
}
jschell Stop using int for one loop counter and long for the other - it's making the 10% difference you were presenting the first time 'round
jschell,
I ran your latest test, but with both loop counters defined to be int and here are the numbers my old pig puts out:
direct = 7291
indirect = 7270
direct = 7241
indirect = 7290
direct = 7210
indirect = 7211
The standard deviation clearly exceeds any difference.
Just out of curiousity, what are you running on?
Ian
Yes, Ian you are correct. In my revised test I inadvertently set both methods to use ints, that is why my tests bore the same equal results as your tests.jschell, hey you almost pulled that one off ;) I'm sure that was accidental, though... right!
Hi ,
Till now from the overall view I am able to
judge that the interface are only the design issues
blocks.In fact I had reffered the design pattern
book from bruceeckel.I have started getting little
clearer about this.
So should I continue with keeping in mind
the interfaces are just required at the design
stage of the oops model with help of which it
will be possible to make the change efficiently.
just merely a design issue as at the beginning
you have just a concept?
vicky
Vicky, you've got it!
I haven't looked at Eckel's patterns book that's still in progress, but it could well be helpful. Also bear in mind that Design Patterns - Elements of Reusable Object-Oriented Software is the book that really brought software design patterns to the wide world. Unfortunately all the examples are in C++ and Smalltalk. You should be able to find it in any decent library or technical bookstore. Also, the same patterns are presented in Java, though I think somewhat less thoroughly inPatterns in Java, Volume 1 - written with the intent not to replace the book above, but to complement it.
I worry a bit that you might be skipping a step, to jump so soon to patterns before getting a good understanding of general OO design. On the other hand, if you find a book on patterns that you can read and understand, then you'll learn tremendously useful examples of how to get the most out of OOD/P.
There is another book I've only heard about, not seen, but it sounds like it might be the perfect book for you: it's A Little Java, a Few Patterns. Read the reviews at amazon.com - think it will appeal to you.
Enjoy your journey...
Ian
>Stop using int for one loop counter and long for the other - it's making the 10% difference
Grrrr!!!!!!
Ok.
Guess I will have to track down the reference and figure out what they were really talking about.
Of course the byte codes are different, so one would presume that some difference should result.
>Just out of curiousity, what are you running on?
This box thingy in front of me?
Or perhaps you had this in mind: NT 4, PIII 866, 512meg.
Hi Ian,
Yes really the concept is commimg,but I am not able
to get an appropriate examples precise the explaination.
Once againg I would like to confirm from you:
1)My understanding till now says that the interfaces
do increase the code,but then they let us the flow
of logic seperable,At the beginning we do develop
only the general entities and start working on that,
2) Although having an experience I find difficult
to find out the behavoir of objects,and I have
read in some resources that the UML does
solve your design aspect.Is this right ,do you create
the case diagrams and all the stuff.
3)I feel working with the uml will give me the clearer
explaination of the interfaces.
4)Lastly I would like to know is it is recommended
to develop a uml diagram for the webbased application.
thanks
vicky
> >Just out of curiousity, what are you running on?
>
> This box thingy in front of me?
>
> Or perhaps you had this in mind: NT 4, PIII 866,
> 512meg.
I was just surprised that with my old machine and using Sun's compiler your numbers were not quite four times faster than mine. Considering how ancient this thing of mine is, I thought everything was at least an order of magnitude faster. Would you believe I'm running with only a 66MHz bus?
Anyway, let us know what you find out about the different bytecodes if manage to dig it up.
Cheers,
Ian
> Hi Ian,
H'lo again Vicky,
> Yes really the concept is commimg,but I am not able
> e
> to get an appropriate examples precise the
> explaination.
> Once againg I would like to confirm from you:
> 1)My understanding till now says that the interfaces
> do increase the code,but then they let us the flow
> of logic seperable,At the beginning we do develop
> only the general entities and start working on that,
> 2) Although having an experience I find difficult
> to find out the behavoir of objects,and I have
> read in some resources that the UML does
> solve your design aspect.Is this right ,do you
> create
> the case diagrams and all the stuff.
To be honest, I've never worked on a project that used the entire UML process from start to finish. The greatest value I get out of UML is in visualizing for myself, and in communicating my designs to others. And it's the class diagrams that I generally use the most, with interaction diagrams for dynamic aspects. But in large part my narrower focus is due to the stages of development with which I'm most involved.
> 3)I feel working with the uml will give me the
> clearer
> explaination of the interfaces.
In learning UML you will learn a lot about OO, and you'll gain the ability to understand other people's UML diagrams in discussions of OO design.
> 4)Lastly I would like to know is it is recommended
> to develop a uml diagram for the webbased
> application.
It depends on the application. If you're working only with simple JSP pages and a few beans that don't really interact with each other then possibly not - at least not the class and interaction diagrams I use most. But if your application includes a fair bit of business logic under the surface, then very definitely yes.
Though I'm not a web-developer myself, I would expect use-cases and state-transition diagrams to be quite helpful during the development of web-apps, even when the object models are simple.
> thanks
> vicky
Cheers, Ian
Ooops, this thread is gaining a much broader focus than expected ;-)
> 1)My understanding till now says that the interfaces
> do increase the code,but then they let us the flow
> of logic seperable,At the beginning we do develop
> only the general entities and start working on that,
Thinking that way, interfaces separate the declaration from implementation details.
Thus, the implementor of a certain method is free in chosing the appropriate algorithms given the interface only and the implementation can be extended/changed.
In oo terms, this concept is also called contracting:
An interface at least declares a contract, a basic functionality, which the implementation has to fulfill.
> 2) Although having an experience I find difficult
> to find out the behavoir of objects,and I have
> read in some resources that the UML does
> solve your design aspect.Is this right ,do you
> create
> the case diagrams and all the stuff.
There are several methods to design software of which UML is the most commonly used.
Think about UML as a description method which makes it easier to understand all aspects of your software.
> 3)I feel working with the uml will give me the
> clearer
> explaination of the interfaces.
Right and wrong ;-)
With UML class diagrams, you get a better overview of a certain software architecture than by looking into code.
However I'd find it difficult to find out how interfaces are working by looking at the UML class diagrams.
But if you feel it is more appropriate for you, go ahead.
> 4)Lastly I would like to know is it is recommended
> to develop a uml diagram for the webbased
> application.
First, all software design methods serve several purposes: To visualize the architecture, help you finding the appropriate relations and behavior, to identify bottlenecks and common mistakes and to build a clean and reusable platform.
A good specification including a good design makes it much easier to refigure and refactor your software at a later point of time.
Software design should be done to give exact guidelines for developers which are responsible for the implementation process. This point is often forgotten, as software desing is often seen as a "must-do-because-the-customer-wants-it" step.
So the aim of a good design is to provide a program structure and instructions for others than for yourself, even if it is yourself who implements it later. It is nothing than some sort of story book.
On the other hand a fully featured design is often not necessary, as some things might be obvious.
To come back to your question, it is up to you to decide which functionality should be documented via UML and which should not.
Be as descriptive as necessary and if you feel that your servlets and JSPs need a description, do not hesitate to use all the tools the UML provides, as there are class, state transition and object/interaction diagrams for example.
Always take in mind, that a good design should be done as if someone else will do the implementation.
Doing that, you do not only do a favor to your customers and everyone reading your software, but also for yourself.
I hope this answers your questions.
Oliver
ofels at 2007-7-2 15:52:36 >

Oliver made lots of good points, but I'll add one more.
Don't just think of design as something that is done first. Think of every bit of code you write as presenting you with design choices. Cut-and-paste "design" is way too popular and it happens at the smallest granularity of development. So design design design whenever you're programming.
Oliver speaks very true that learning UML won't necessarily teach you about interfaces. What you want to do is learn OO design in general, possibly using UML. The only effective way is through experience, so you would do well to take a good quality course with assignments that make you implement your designs using an OO language like Java(not C++, it'll confuse you for sure).
Ian
>Anyway, let us know what you find out about the different bytecodes if manage to dig it up.
Eh? Like I said the byte codes are different. How they are implemented is the question.
From "Inside the Java Virtual Machine 2 edition", Chapter 19
--
Invocation Instructions and Speed
As you might imagine, invoking a method given an interface reference is likely slower than invoking a method given a class reference. When the Java Virtual Machine encounters an invokevirtual instruction and resolves the symbolic reference to a direct reference to an instance method, that direct reference is likely an offset into a method table. From that point forward, the same offset can be used. For an invokeinterface instruction, however, the virtual machine will have to search through the method table every single time the instruction is encountered, because it can't assume the offset is the same as the previous time.
--
Keep in mind that I don't consider this book a real resource since most (all?) of the stuff it covers, contains no actual references to real VMs. But the words sounded good.
