Q

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. 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

Dig deeper on Java Web Services

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

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:

SearchSoftwareQuality

SearchCloudApplications

SearchAWS

TheServerSide

SearchWinDevelopment

Close