Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

How to pass a class name to the constructor of another class?

user543623Jul 22 2023

Hello,

How to pass a class name to the constructor of another class?

I have three classes below: A, B, and Main. I would like the Class A constructor to accept a class name as a parameter. When I create an object of class A, I should be able to pass the name of the actual class (B, in this case). Then, obj should be able to access the methods of class B.

How can I achieve it? Thank you!

class A{

// constructor with param
A( "add param here"){

}

// Add getter method

public className getClassName(){

return className;

}

}

class B{

// method 1

// method 2

}

class Main{

A obj = new A("B");

// obj.method1();
// obj.method2();

}

Comments
Post Details
Added on Jul 22 2023
2 comments
457 views