











Java Object getClass()


What is a Object in Java?
In Java, an object is an instance of a class. A class is a blueprint or template that defines the properties and methods of an object. An object is created from a class and can be used to access the properties and methods of that class.
- An object in Java is created using the new keyword, followed by the class name and constructor.
To know more about Object toString in java read the complete article.
Object getClass() method.
In Java, the getClass() method is a method that is defined in the Object class, which is the parent class of all classes in Java. It returns the Class object that represents the runtime class of the object on which the method is called.
- The Class object returned by the getClass() method provides information about the class, such as its fully qualified name, its constructors, methods, and fields. It also provides methods to perform reflection on the class, such as creating new instances of the class, invoking methods, and accessing fields.
Syntax:
public final Class<?> getClass()
Parameters:
The getClass() method does not take any parameters.
Let’s look at a object-related Java program where the Java object getClass Method is used to perform an operation on the given object.
Example: Java Object getClass() Method
class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } } public class Main { public static void main(String[] args) { Person person = new Person("John", 30); Class c = person.getClass(); System.out.println("Class Name: " + c.getName()); } }
Output
Class Name: Person
Example 2 : Java object getClass() Method
public class Main { public static void main(String[] args) { Object obj = new Integer(5); Class c = obj.getClass(); System.out.println("Class Name: " + c.getName()); } }
Output
Class Name: java.lang.Integer
Example 3: how to use the object getClass property:
class MyClass { private String message; public MyClass(String message) { this.message = message; } public String getMessage() { return message; } } public class Main { public static void main(String[] args) { MyClass obj = new MyClass("Hello World"); Class c = obj.getClass(); try { MyClass newObj = (MyClass) c.getConstructor(String.class).newInstance("This is a new object"); System.out.println("New Object Message: " + newObj.getMessage()); } catch (Exception e) { e.printStackTrace(); } } }
Output
New Object Message: This is a new object
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment