What is the differnce between the below two delcarations
class1 x = new class1();
interface1 x = new class1();
The most basic difference that I see is that you can carry the object. For example, we have a Math interface, and an Add class implementing it. Let there be another class ZigZag implementing Math interface, that has some specific functionality.
The doSomething() method in ZigZag class does not know if the parameter is coming from Add class or some other class, it only knows that the incoming parameter must be of Math type (specifically any class implementing Math interface). So, z.doSomething(a1); will not work. Hence you could move object in your application easily and knowingly.
I had a method in class which was not delcared in interface. But When i delcare a variable of type interface1 x, i am still able to access that method. How??
Considering the method is not declared in interface,
• and it is of instance type, then the method in the object's type (class) will be invoked. Instance methods are executed based upon the object used to invoke it.
• and it is of static type, then it will lead to compiler error. The method with same signature must be present in the interface. Static methods are executed based upon the type of the variable or if accessed directly like , the object's type's or its super-class's static myMethod() will be invoked.
Go with my English literature and try some examples on your own.
The biggest gamble will be to ask a question whose answer you know in that it will challenge your theory | www.TechAspire.blogspot.in
Joined: Dec 26, 2012
Thanks for the reply. You answered my doubt precisely.
Also...remember that in the 'real world', most of the time you will not be writing all the code. It is common for different groups to work on different parts of the code. In fact, code could be written by a group in a completely different company.
Using interface names allows that other group/company make changes to their side without you worrying about your code.
You can think of an interface as being similar to a physical USB port. Let's say I am going to get some data from a service on a weekly basis. By using a USB interface, they can send me a thumb drive, a cell phone, an external hard drive, or hundreds of other possible devices. I don't really care, as long as it uses a USB.
By using an interface in Java, this other group can change the underlying object type and how it does its work behind the scenes. As long as it still implements the Java interface, I can 'plug it in' to my code and not care about anything.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
subject: what is the advantageDeclaring variables with interface names