Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6210053
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T06:05:36+00:00 2026-05-24T06:05:36+00:00

I don’t know if I’m missing something here, but I am having trouble casting

  • 0

I don’t know if I’m missing something here, but I am having trouble casting an object to its actual, initialized type. Basically, if I create an object with “SuperClass sc = new SubClass(),” then I call a method on sc, I want the method to be able to call method(Subclass) instead of method(Superclass). Example shown below:

public class Example
{
    public static void act(SuperClass a) {
        System.out.println("SuperClass");
    }

    public static void act(SubClass a) {
        System.out.println("SubClass");
    }

    public static void main(String[] args) {
        SuperClass sc = new SubClass();

        // want to find a way to call act(SubClass) instead of act(SuperClass)
        act(sc);
   }
}

class SuperClass {}
class SubClass extends SuperClass {}

I am using the visitor pattern right now, but I’m wondering if there are other ways to do this, maybe via the Java Reflection API?

Thanks alot in advance!

== edit ==

I know that generally with OO it’s better to stick the functionality back to the superclass/subclasses themselves, but for my specific use cases I have a bunch of subclasses that are immutable model classes, which should be passed to different kinds of execution engines (think different “Example” classes). The subclasses/model classes should only hold immutable information, nothing more, and the actual real functionality lies with the execution engine (Example class). That’s why I am wondering about alternatives to the visitor’s pattern. Does anyone have a way to recover the actual “initialized” information in Java? If so, thank you so much.

And because of the nature of the problem, I can’t use direct casting…
Imagine if I have an arraylist of SuperClass, where each element may be SubClass1, SubClass2, SubClass3, all extending from SuperClass.

Now, when you pull things out of the Arraylist, you get a SuperClass object, even though they may really be SubClass1, SubClass2, SubClass3, etc.

Next, I want to call act(SubClass1), and be able to invoke the correct act() method on the current type. So I want to end up calling act(SubClass1), act(SubClass2), act(SubClass3), instead of act(SuperClass).

== edit again ==

I’ve came up with a way of doing this via the Java Reflection API, by finding the actual underlying type of the SubClass using Class.forName(classname), then dynamically invoking the method with the correct method signature. I have written this up in answer form somewhere down this page for those who are interested about this problem. Note that this isn’t a very efficient way of accomplishing what I’m trying to do here, and you’re probably better off with visitor pattern or if-else statements if you’re stuck with my situation.


So the answer that Nicola Musatti gave is the closest to answering my question, though as he has also pointed out, as the number of SubClasses grow the if-else statements list gets very long. I will choose his answer as the accept answer since I hadn’t stated clearly in my question that I was hoping to avoid the if-else checks.

Anyways, so I’ve played around a bit with the Java Reflection API today and came up with this:

SuperClass sc = new SubClass();

// Get the actual class of sc. actualClass now is SubClass.
Class actualClass = Class.forName(sc.getClass().getCanonicalName());

// Basically invoking act(SubClass sc) instead of act(SuperClass sc)
Class parameters[] = {actualClass};
Method method = Example.class.getMethod("act", parameters);
Object arguments[] = {sc};
method.invoke(null, arguments);

This is surely not a great way to do things, especially because of the performance penalty impose by the Java Reflection API. This might be better than visitor pattern or the if-else checks if you have a million subclasses, since it’s probably less code to manage, however I’ll stick with the visitor pattern for now since I don’t have a million subclasses to manage.

Regardless, just thought I would post this here to show that it can be done, just for those who are curious.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T06:05:36+00:00Added an answer on May 24, 2026 at 6:05 am

    The general solution is the Visitor pattern. If you have a specific situation where you know the actual type of sc you can indeed use a cast, as was already suggested, possibly preceded by a type check as in

    if ( sc instanceof SubClass ) act((SubClass)sc);
    

    However the Visitor pattern was invented because this approach doesn’t scale up when the number of classes you need to handle grows.

    Last but not least, sometimes the simplest approach is just to keep around a variable of the actual type:

    SubClass scc = new SubClass();
    SuperClass sc = scc;
    act(scc);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Don't know whether I'm having a "thick day" - but I just wondered what
Don't really know how to formulate the title, but it should be pretty obvious
Don't know how to google for such, but is there a way to query
Don't know whats exactly going on, but it's definitely killing my time for nothing.
I don't know if thats right but for some reason my stored procedure is
Don't know what's wrong here, when I run the application it says Specified method
Don't know if this is the right place to ask this, but I will
Don't know why, but sometimes LocationManager is still working also after closing application. I
Don't know if this is an eclipse specific problem but whenever I declare a
I don't know if this has been asked before, but what i'd like to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.