【问题标题】:Need to call one sub class of an interface using object of another sub class需要使用另一个子类的对象调用接口的一个子类
【发布时间】:2015-03-11 14:06:23
【问题描述】:

我有一个interface

public interface I
{
    // an abstract method m1();
}

我有classAclass B

class A implements I
{
    public void m1()
    {
         System.out.println("m1 Method From A");
    }
}

class B implements I
{
    public void m1()
    {
        System.out.println("m1 Method From B");
    }
}

我可以使用创建到class Aobject 调用class Bm1 方法吗?

例如,我创建了objectA,例如I i = new A();

如果我写成i.m1() m1 应该调用class B 的方法

注意:class Aclass B 之间没有 super class or sub class 关系

我能不能打电话只是个疑问

谢谢...

【问题讨论】:

    标签: java class interface


    【解决方案1】:

    您需要将B 类型的依赖项/关联添加到A。这可以通过在A 中引入B 类型的类成员来轻松完成

    类似这样的:

    class A implements I
    {
        private B b = new B();
    
        public void m1()
        {
             System.out.println("m1 Method From A");
             b.m2();
        }
    }
    

    【讨论】:

    • 感谢您的回答,但我怀疑我是否可以在不创建 objectclass B 的情况下调用 m1()class B
    • 此解决方案使用关联。没有关联就不能从 A 调用 B 类的 m1()。
    【解决方案2】:

    你可以使用反射:

    界面

    public interface I {
        public void m1();
    }
    

    A类

    public class A implements I
    {
        public void m1()
        {
            System.out.println("m1 method from A");
            
            try {
                Method sampleMethod = B.class.getMethod("m1" , new Class[] {});
                sampleMethod.invoke(B.class.newInstance()); 
            }
            catch(Exception e) {
            }
        }
    }
    

    B 类

    public class B implements I {
        public void m1() {
            System.out.println("m1 method from B");
        }
    } 
    

    主要

    public static void main(String[] args) {
         A a = new A();
         a.m1();    
    }
    

    操作:

    来自 A 的 m1 方法

    来自 B 的 m1 方法

    【讨论】:

      猜你喜欢
      • 2015-08-18
      • 1970-01-01
      • 2019-07-25
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 2020-09-13
      相关资源
      最近更新 更多