【问题标题】:Inheriting from two classes with Java?用Java继承两个类?
【发布时间】:2012-11-28 06:40:41
【问题描述】:

我创建了一个类来包含一个带有我的应用程序徽标的自定义标题栏。这很好用,除了对于我的大多数类,我需要能够继承该功能以及 ListActivity 的功能。怎么办?

任何帮助表示赞赏。

【问题讨论】:

  • 标记 android 并没有指定您使用哪种语言进行编码,但我假设 java 中不可能有多重继承。你需要改变你的设计。
  • 使用组合而不是继承。 Java 不允许状态的多重继承。
  • 即便如此,您可能仍想使用合成。
  • 如果你想在单个类中继承两个类,那么使用 C++ 创建你的类,使用 JNI 和 NDK 来访问 java 代码中的这些类行为或属性。因为 java 不允许多重继承

标签: java android oop design-patterns multiple-inheritance


【解决方案1】:

在 Java 中,您不能拥有:

class MyClass extends ClassA, ClassB { ... }

根据你在做什么,可能会使用:

class ClassB extends ClassA { ... }

class MyClass extends ClassB { ... }

【讨论】:

  • 我们可以使用 NDK 和 C++ 而不使用接口来做到这一点吗?
【解决方案2】:

你应该更喜欢组合(和委托)而不是继承:

   public interface FirstClassInterface {
       void method1();
   }

   public interface SecondClassInterface {
       void method2();
   }

   public class FirstClass implements FirstClassInterface {
       // ...
   }

   public class SecondClass implements SecondClassInterface  {
       // ...
   }

   public class FirstAndSecondClass implements FirstClassInterface , SecondClassInterface       
    {
       private FirstClassInterface firstclass;
       private SecondClassInterface secondclass;

       public FirstAndSecondClass(FirstClassInterface firstclassinterface, SecondClassInterface   secondclassinterface) {
           this.firstclass= firstclassinterface;
           this.secondclass= secondclassinterface;
       }

       public void method1() {
           this.firstclass.method1();
       }

       public void method2() {
           this.secondclass.method2();
       }

       public static void main(String[] args) {
           FirstAndSecondClass t = new FirstAndSecondClass(new FirstClass(), new SecondClass());
           t.method1();
           t.method2();
       }
   }

【讨论】:

    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 2017-12-27
    • 2011-09-04
    • 2015-04-09
    • 1970-01-01
    • 2010-09-23
    • 2021-09-12
    • 2011-06-03
    相关资源
    最近更新 更多