Welcome to the Ranch.
What is the differnce between the below two delcarations
class1 x = new class1();
and
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.