Differences between compile-time and run-time inheritance

Differences between compile-time and run-time inheritance

Can you please differentiate with examples between compile-time inheritance and run-time inheritance and please specify which Java supports.

    Requires Free Membership to View

    When you register, you'll begin receiving targeted emails from my team of award-winning writers. Our goal is to keep you informed on recent service-oriented architecture (SOA) and SOA-related topics such as integration, governance, Web services, Cloud and more.

    Hannah Smalltree, Editorial Director

    By submitting your registration information to SearchSOA.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchSOA.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

The term "inheritance" refers to a situation in which attributes and/or behaviors are passed on from one object to another. When this occurs at compile-time, it is usually called "subclassing" since one class, the child, is lower than the parent in the inheritance hierarchy. The Java programming language reserves the keyword "extends" for compile-time inheritance. The following example in Java shows how a child class, B, inherits attributes and behavior from the parent class, A.

public class A
{
   public String sayHello()
   {
      return "Hello";
   }
}

public class B extends A
{
   public String sayHello()
   {
      return super.sayHello() + " world!";
   }
}

In the above example, a call to the sayHello method of class B will return "Hello world!", since class B "inherits" the "Hello" from class A. Notice that the keyword "super" is used to call the method on the parent class.

Runtime inheritance refers to the ability to construct the parent/child hierarchy tree at runtime. While Java does not allow this natively, there are a number of projects and technologies available that will enable you to modify the bytecode of a class after compilation. While they really aren't intended to use for runtime inheritance, they could do the job.

An alternative to native runtime inheritance is a concept known as "delegation", which refers to constructing a hierarchy of object "instances" at runtime. This technique will allow you to simulate runtime inheritance. In Java, delegation is typically achieved in a manner similar to the following:

public class A
{
   public String sayHello()
   {
      return "Hello";
   }
}

public class B
{
   public String sayHello()
   {
      return new A().sayHello();
   }
}

This was first published in August 2004