Ask the Expert

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

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: