How to Combine Classes in Java

Programmers use the Java programming language, in part, because of its complete support of an object-oriented programming paradigm. Because of this, they can create different data objects and build an extensive library of already-existing classes. However, should the need to combine classes arise, there are three options available. The first is to set up a hierarchy of derivation, in which a target class derives from a series of related classes. The second is to include classes within your class in order to use their functionality. The third is to create a number of "interfaces" rather than classes, and implementing those interfaces.

Things You'll Need

  • Java Development Kit (JDK)
  • Text editor or Java interactive development environment
Show More

Instructions

    • 1

      Create your Java class. This class will be the one that "combines" the other classes:

      public class MyClass {
      /*implementation code of MyClass goes here*/
      }

    • 2

      Extend a hierarchy of inheriting classes. In Java, the only way for your class to inherit functionality from other multiple classes is if those classes all inherit from each other in a linear fashion. For example, if you want "MyClass" to inherit functionality from "Class1" and "Class2," and Class2 already inherits data from Class1, then MyClass can gain the functionality of both by extending Class2:

      public class MyClass extends Class2{
      /*implementation code of MyClass goes here*/
      }

    • 3

      Use classes inside your class. If Class1 and Class2 are unrelated, meaning they do not share data through inheritance, then you can use objects of Class1 and Class2 inside MyClass to gain access to their functionality:

      public class MyClass {
      public Class1 x = new Class1();
      public Class2 y = new Class2();
      /*implementation code of MyClass goes here*/
      }

    • 4

      Use interfaces instead of classes. If Class1 and Class2 are interfaces, meaning that they only supply a group of methods to implement rather than define them, then MyClass can implement both of them. A class can implement any number of interfaces, so long as it implements the methods defined in the interfaces:

      public interface Class1 {
      /*function declarations*/
      }

      public interface Class2 {
      /*function declarations*/
      }

      public class MyClass implements Class1, Class2 {
      /*implementation code of MyClass goes here*/
      }

Related Searches:

References

Comments

Related Ads

Featured