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 last published in August 2004

Dig Deeper on Java Web Services

PRO+

Content

Find more PRO+ content and other member only offers, here.

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.

Start the conversation

Send me notifications when other members comment.

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

Please create a username to comment.

-ADS BY GOOGLE

SearchSoftwareQuality

SearchCloudApplications

SearchAWS

TheServerSide

SearchWinDevelopment

Close