Google+

125. Interface References






Declaring an object as Interface type instead of class type as shown in the example below:

Interface1 object1 = new ClassOne( );    //object1 is declared as Interface type instead of Class type

We can use this object1 to access the overridden instances of any class which implements this Interface1.

Lets implement this on Eclipse IDE:

1.Create Interface 'Interface1' which declares a method 'sample( )' as shown below:



2. Create class 'ClassOne' which implements the 'Interface1' as shown below:



3. Create class 'ClassTwo' which implements the 'Interface1' as shown below:



4. Create class 'ClassThree' which implements the 'Interface1' as shown below:



5. Create class 'InterfaceReferenceDemo' to create Interface object and access the instances of implementation in ClassOne, ClassTwo and ClassThree as shown below:



6. Save and Run the 'InterfaceReferenceDemo' class
7. Observe that the output is displayed in the console as shown below:





Download this project:

Click here to download the project containing the 'InterfaceReferenceDemo', 'Interface1', 'ClassOne', 'ClassTwo' and 'ClassThree' files used in this post (You can download this project and import into Eclipse IDE on your machine)

We can also achieve the same result by assigning the Class objects to the Interface object.

Lets implements this on Eclipse IDE:

1. In the above project, edit the 'InterfaceReferenceDemo' class file as shown below:



2. Save and Run the 'InterfaceReferenceDemo' class
3. Observe that the output is displayed in the console as shown below:



Download this project:

Click here to download the project containing the class files used in this post (You can download the project and import into Eclipse IDE on  your machine)



Please comment below to feedback or ask questions.

Abstract methods in Superclass must be implemented in Subclass will be explained in the next post.




No comments: