有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java类外的访问接口

我有一个类A,另一个是B,只有一个接口Ai和一个方法ok()

A级实现人工智能,在ok内部,我只打印一行

B类有A的实例,我想访问B中A的接口Ai。

能做到吗?如果是,怎么做

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();
}

共 (2) 个答案

  1. # 1 楼答案

    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);
       }
     }
    }
    

    我只需要这个。你有疑问吗?请评论

  2. # 2 楼答案

    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();
            //just call a.ok() here to execute A implementation of Ai.ok()
            a.ok(); // < - 
        }
    }
    
    interface Ai{
        public void ok();
    }