Skip to content
Advertisement

access interface out of the class java

I have a class A, another is B, there is one interface Ai with one method ok() only.

Class A implements Ai, inside the ok I’m printing just a line.

Class B has an instance of A, I want to access A’s interface Ai inside B.

Can it be done ? If so how ?

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");
        new B();
     }
}

class A implements Ai{
    
    public A(){
        ok();
    }
    
    @Override
    public void ok(){
        System.out.println("ok???");
    }
}

class B{
    public B(){
        A a = new A();
        // I want to call interface of A from here,
        // so I can get the exact ok method of A
        // that print's "ok???" from inside class B
    }
}

interface Ai{
    public void ok();
}

Advertisement

Answer

class A implements So{
 B b;
 @Override
 so(int x){
   if(b!==null){
     b.so(x);
   }
 }
}
class B implements So{
 A a;
 @Override
 so(int x){
   if(a!==null){
     a.so(x);
   }
 }
}

All I needed is this. Have query? Comment please.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement