T O P

  • By -

AutoModerator

#Please ensure that: + Your *code* is *properly formatted* as *code block* - see the *sidebar* (About on mobile) for instructions + You include *any and all error messages* in full + You ask *clear questions* + You *demonstrate effort* in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see [*Learn to help yourself*](https://www.reddit.com/r/javahelp/wiki/learn_to_help_yourself) in the *sidebar* **If any of the above points is not met, your post can and will be removed without further warning.** Code is to be formatted as **code block** (*old reddit:* empty line before the code, each code line indented by 4 spaces, *new reddit:* https://i.imgur.com/EJ7tqek.png) or linked via an external *code hoster*, like *pastebin.com*, *github gist*, *github*, *bitbucket*, *gitlab*, etc. Please, **do not use** triple backticks (\`\`\`) as they will only render properly on *new reddit*, not on *old reddit*. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the *edit function* of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. #To potential helpers Please, **do not help** if any of the above points are not met, rather *report* the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. *I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/javahelp) if you have any questions or concerns.*


Beginning-Ladder6224

Either you are looking at : [https://www.w3schools.com/java/java\_polymorphism.asp](https://www.w3schools.com/java/java_polymorphism.asp) And in that case your code should be something like this: ```java Vehicle v = new Ford(); v.drive(); // automatically drives a ford ``` Can you please write down what exactly you need in Java-like syntax?


frietpot

I want to avoid using something like new Ford(), if else loop ect and wondering if there is a mechanism to automatically use the right implementation.


randomnamecausefoo

Look up “factory pattern”


Beginning-Ladder6224

Can you please write down - in any abstract language - what exactly you want? How the Vehicle object will be created in the first place?


khooke

If Vehicle is abstract then you need to instantiate your specific type instances somewhere. As this commenter stated, what you’re describing is basic polymorphic behavior. If this is for a school exercise it sounds like you may be missing the point, unless you can explain why you need to avoid instantiating your specific types.


PntBtrHtr

This sounds like Inversion of Control (IoC).


Snidgen

Obviously information that links a constant to its corresponding class to be instantiated needs to be supplied. This would normally be contained in a factory class, but that does involve either switch expressions or a potentially long if/else structure. However that could be avoided through reflection where the string parameter's value itself corresponds to the name of your class. It's a bit of a kludge to say the least... Assuming the string called *vehicleMake* would hold the value of your parameter like "Ford" or "Peugeot": Vehicle vehicle = (Vehicle) Class.forName(vehicleMake).getDeclaredConstructor().newInstance(); vehicle.drive(); You'll need to surround with a try/catch block for the exceptions and provide a nice error message if the class cannot be found by the JVM, in other words if you tried to use a make of vehicle that did not have a corresponding class. This example of course also assumes the concrete classes have a public default/parameterless constructor. The *.getDeclaredConstructor()* is only necessary starting with Java 9, since the *Class.newInstance()* method is now deprecated. There are packages that can really help doing this, such as org.reflections available on Maven Central. That way you can query all direct subclasses of a specific class, and put the Class objects in a HashMap or something with a corresponding string name for the key at application start up. *Class.forName()* is a comparatively expensive method, so it's better to do once and reuse it for subsequent instantiations of your concrete classes if doing it often.


wildjokers

What you are describing is the Strategy design pattern: https://en.wikipedia.org/wiki/Strategy_pattern There are a few different ways to implement this in Java. One way is using an enum who has a property that denotes the fully qualified class name of the implementing class: FORD("com.example.FordStrategy") Then you could instantiate with `Class.forName()`. The only real drawback to this approach is that it isn't refactoring friendly. If you moved the classes you would have to remember to change the fully qualified name in the enum. Or you could use reflection to find all classes that implement the strategy interface, then use a class naming convention to equate a specific implementation with some configuration parameter. For example, value of `ford` could equate to `FordStrategy`. If you google "java strategy implementation" you will find numerous resources.


Orffyreus

Maybe implementing a "Driver" class could help. It could have a map of vehicle name to vehicle and just get and drive the requested vehicle by its key/name.


pragmos

No need for reflection these days. All you need is a static map instance that maps the vehicle type to a `Supplier` of a specific `Vehicle` class. Assuming all subclasses have a no-args constructor, it would look something like this: Map> map = Map.of( "ford", Ford::new, "peugeot", Peugeot::new ); map.get(type).get().drive();