11-02-25 ---------- Interfaces(upto Java SE 7) ----------------------------- Q)What is an interface? =>An interface is a class like construct in Java. =>An interface has methods and variables*. =>An interface is compiled to ".class" file. =>An interface acts a user defined data type. =>Members of an interface are implicitly public. =>methods are implicitly abstract. =>variables are implicitly static and final. I.e. an interface can have only constants. interface I{ int a=10;//public static final variable void x();//public abstract method } =>A class can inherit from an interface using the keyword "implements". =>When a class is implementing an interface, it is the responsibiity of that class to override(implement) all the abstract methods of that interface. Otherwise, that class becomes abstract. =>An interface can inherit from another interface using the keyword "extends". interface I1{ } interface I2 extends I1{ } =>A class can inherit from any number of interfaces. interface I1 { } interface I2 { } class A implements I1,I2 { } Q)What is the implementation class of an interface? =>sub class (child class) of the interface is known as implementation class. Q)What is wrong with the following code? interface I{ int a; private int b=10; void y() { } } Ans:- 1)only constants are allowed. int a;//it is just a variable but not a constant 2) private modifier is not allowed for the members of an interface 3)inteface methods cant have body. Q)What is wrong with the following code? interface I { void x(); } class A implements I { }//implementation class(sub class) Ans:- In class A, x() method should be implemented or declare class A as abstract Q)What is wrong with the following code? interface I { void x(); } class A implements I { void x() { System.out.println("implementation of x method"); } } Ans:- In the child class, accessibility mode of x() method is reduced to default. make it public. Q)What are the similarities between an abstract class and an interface? =>Both can have abstract methods. =>Both can't be instantiated. =>Both act as user defined data types and therefore references of both of them can be created. =>Both can be inherited.In fact, both are meaningful only in the context of inheritance. Q)What are the differences between an abstract class and an interface? abstract class interface ******************************************** 1)partially abstract fully abstract 2)members have public mode default accessibility mode. 3)Can't participate supports declarative multiple inheritance in multiple inhertitance 4)Can have all types only constants of variables 5)methods are not implicitly abstract implicilty abstract. 6)can have constructor can't have 7)fecilitates generalization fecilitates standardization ********************************************** Q)What is an interface object? =>In fact, object of an interface can't be created. =>Interface object means reference is of interface type but the object is of its implementation class type.