Monday 18 October 2021

Interface java Example Interview

 //interface Only public, static and final are allowed.

//No. Interfaces can’t have constructors.
interface Test{

static int s=2;
final int d=4;
void get();
int getmultiple();

}


// initializers not allowed in interfaces
/*interface demoStatic(){
{ System.out.println("empty implemented");}

static{
System.out.println("static implemented");
}
}*/


interface B{
int getdivide(int i);
// int getadd();//implementation is required in Class A
}

class A implements B{

public int getdivide(int i ){
return i*i;
}
}


class p{

interface Q{
int i=111;
}
}

interface NextTest extends Test{
int t=5;
void get();

int getadd();

// int getValue();//Demo is not abstract and does not override abstract method getValue() in NextTest
}

class Demo implements Test, NextTest {

public int getadd(){
return d+t;
}

public int getmultiple(){
return d*t;
}
public void get(){
System.out.println("demo get method implemented");
}


}
class XDemo extends Demo{

}

/*class XXDemo implements NextTest{
void methodD(){
i=4;
//No, because interface fields are static and
//final by default and you can’t change
//their value once they are initialized. In the above code, methodB()
//is changing value of interface field A.i. It shows compile time error.
}
}*/


public class MyClass {
public static void main(String args[]) {

System.out.println("Interface");

Test s=new XDemo();
s.get();
// System.out.println("sum : "+ s.getadd());//it will check in Test interface error not found

System.out.println("multiple : "+ s.getmultiple());
NextTest st=new XDemo();
System.out.println("add : "+ st.getadd());

// XDemo s=new NextTest();//NextTest is abstract; cannot be instantiated
XDemo sp=new XDemo();
System.out.println("addd : "+ sp.getadd());
System.out.println("multiple : "+ sp.getmultiple());



B newS=new A();

System.out.println("divide : "+ newS.getdivide(12));
// p ps=new Q();
B bs=new B(){
public int getdivide(int i){
return i*i; }

};

System.out.println("divide : "+ bs.getdivide(12));
}
}

No comments:

Post a Comment