• Twitter
  • Facebook
  • Google+
  • Instagram
  • Youtube

Wednesday, June 10, 2015

difference between creating an object with class and interface reference in java

//Interface Inn
package com.saa.com;
    public interface Inn {
    public void display();
    }

//class A

package com.saa.com;

 public class A implements Inn{

@Override
public void display() {

System.out.println("====A display====");
}
public void a_display(){
System.out.println("====Non Interface method display====");
}
}


// class B
package com.saa.com;
public class B implements Inn{
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("====B display====");
}
}

//Class C
package com.saa.com;
public class C {

public static void main(String[] args) {
// TODO Auto-generated method stub

/* An interface reference can point
to any object of a class that implements this interface*/
//case 1:
A a=new A();
a.display();
a.a_display(); // non interface method.
//output  :  ====A display====
/* Exp: In the above code we defined reference variable "a" as A class type,
   in order to call display() method which A class implemented.*/
//case 2: Now if we want to use display method in B class we will do following code
B b=new B();
b.display();
//output     :  ====B display====
/*   Exp: In the above code we defined reference variable "b" as B class type,
    in order to call display() method which B class implemented. */
Inn i=new A(); //new B() to access B class display()
i.display();
/*i.a_display(); this gives an error, since interface reference cannot
point to non interface methods*/
//output  :  ====A display====
/* Exp: The above code states that object of "A" class was stored in "i" variable
 which is of "Inn" interface type. Since A implements Inn, so Inn type variables
 can call all methods in that Interface. 
 
 So display() which belongs to Inn and implemented by A class can be accessed 
 by "i" varable. 
 this results i.display() to give output "====A display====".
in case2:
 Now if I want to access display() in B implementation we simple need
 TO CHANGE ONLY ONE LINE " ie OBJECT CREATION"
 Inn i= new B();
i.display();
//output  :  ====B display====
 */
   
/*Now we can state that "Inn" Interface reference "i" is going point any
class object "A" or "B" that implements "Inn"
NOTE: AN INTERFACE REFERENCE CANNOT POINT TO NON INTERFACE METHODS IN A CLASS 
*/
}

}

Contact

Get in touch with me


Mail

just4satyam@gmail.com