Sunday, November 23, 2014

Finding superclasses of an object in Java

In this article, we look into one of the mechanism of an Reflection to find about the super classes of any object in Java with example.  Reflection enables what is commonly referred to as dynamic programming in Java. Reflection in Java is accomplished using the Java Reflection API

Reflection is a mechanism for discovering data about a program at run-time. The most basic thing you usually do when doing reflective programming is to get a Class object. Once you have a Class object instance, you can obtain all sorts of information about the class and even manipulate the class.

Finding Superclasses
The ancestors of a given class are referred to as that class’s superclasses. Using reflection, you can determine all of the ancestors of a given class. After you've obtained a Class object, you can use the getSuperclass() method to get the class’s superclass if one exists. If a superclass exists, a Class object will be returned. If there is not a superclass, this method will return null. Remember that Java supports only single inheritance, so for any given class, there can be only one superclass.  Actually to be clear, there can be only one direct superclass.Technically, all ancestor classes are considered to be superclasses of a given class.To retrieve all ancestor superclasses, you would recursively call the getSuperclass() method on each Class object that is returned.

Here is an example, that explain the above concept 

Example 2 In this example, we try to find the super classes of BigDecimal class. 

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.