- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Demonstrate getting the immediate superclass information in Java
The immediate superclass information of any entity such as an object, class, primitive type, interface etc. can be obtained using the method java.lang.Class.getSuperclass().
A program that demonstrates this is given as follows −
Example
package Test; import java.lang.*; class Class1{ } class Class2 extends Class1{ } public class Demo { public static void main(String args[]) { Class1 obj1 = new Class1(); Class2 obj2 = new Class2(); Class c; c = obj2.getClass(); System.out.println("The class of object obj2 is: " + c.getName()); c = c.getSuperclass(); System.out.println("The super class of object obj2 = " + c.getName()); } }
Output
The class of object obj2 is: Test.Class2 The super class of object obj2 = Test.Class1
Now let us understand the above program.
First the classes class1 and class2 are defined. A code snippet which demonstrates this is as follows −
class Class1{ } class Class2 extends Class1{ }
In the method main(), the objects obj1 and obj2 of classes class1 and class2 are defined. Then getClass() is used to obtain the class of object obj2 and getSuperclass() is used to obtain the super class of object obj2. A code snippet which demonstrates this is as follows −
Class1 obj1 = new Class1(); Class2 obj2 = new Class2(); Class c; c = obj2.getClass(); System.out.println("The class type of object obj2 is: " + c.getName()); c = c.getSuperclass(); System.out.println("The super class of object obj2 = " + c.getName());
Advertisements