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 552865
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T11:32:42+00:00 2026-05-13T11:32:42+00:00

Consider the following code: public abstract class Base { public void getAnswer(); } public

  • 0

Consider the following code:

public abstract class Base {
       public void getAnswer();
}

public class Derived1 extends Base {
       public void getAnswer() {
       }
}

public class Derived2 extends Base {
       public void getAnswer() {
       }
}


public class Main {

   public final int DERIVED1 = 1;
   public final int DERIVED2 = 2;

   public Base b;

   public static void Main() {

      int which_obj = which();

      switch (which_obj) {
      case DERIVED1: Derived1 derived1 = new Derived1();
                     // construct object
                     b = derived1;
                     break;
      case DERIVED2: Derived1 derived1 = new Derived1();
                     // construct object
                     b = derived2;
                     break;
      }

      b.getAnswer();
   }
}

here we are using a switch case to decide what object to construct and accordingly we construct it and assign it to b so as to use polymorphism.

what advantage is polymorphism giving us here?

Now is there a method by which we can avoid the switch case.
say: there is a mapping from int to String that returns “Derived1” or “Derived2”.
given the string containing the name of the class. now can i construct an object given the String containing the name of the class. something like:

Base b = construct_obj(str);

the library call construct_obj automatically locates the class of obj from the bytecodes and returns a reference to the object. then i can avoid the switch case. typically i would be having 100’s of Derived classes.

  • 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-13T11:32:42+00:00Added an answer on May 13, 2026 at 11:32 am

    Well, you could create a Map<Integer, Class<? extends Base>> and then use Class.newInstance to create the instance with reflection. It wouldn’t perform as well, and there are various errors which wouldn’t be exposed until execution time, but it would work.

    Here’s some sample code.

    import java.util.*;
    
    abstract class Base {}
    class Derived1 extends Base {}
    class Derived2 extends Base {}
    
    public class Test
    {
        public static void main(String[] args)
        {
            Map<Integer, Class<? extends Base>> map = 
                new HashMap<Integer, Class<? extends Base>>();
    
            map.put(1, Derived1.class);
            map.put(2, Derived2.class);
    
            int which = 2; // For example
    
            Class<? extends Base> clazz = map.get(which);
            if (clazz == null)
            {
                // Invalid choice. Do whatever.
            }
            else
            {
                try
                {
                    Base base = clazz.newInstance();
                    // Use base
                }
                catch (InstantiationException e)
                {
                    // Handle exception or whatever
                }
                catch (IllegalAccessException e)
                {
                    // Handle exception or whatever
                }            
            }
        }
    }
    

    Note that if you’ve got a contiguous range of integers, you could use an array instead of a map.

    Another alternative is to have factory instances rather than using constructors – this would be “safer” (in terms of not deferring errors) but probably significantly more code. (In C# it would be easy using lambda expressions; Java 7 may make this a preferable solution too.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 426k
  • Answers 426k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer OK i sorted it out Bitmap b=BitmapFactory.decodeResource(CON.getResources(),R.drawable.deltio); Bitmap bmOverlay =… May 15, 2026 at 12:45 pm
  • Editorial Team
    Editorial Team added an answer There are two main ways this is usually done: if… May 15, 2026 at 12:45 pm
  • Editorial Team
    Editorial Team added an answer Please include the version of Ruby you are using for… May 15, 2026 at 12:45 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.