Using variables for creating objects and calling methods in Java

Jagadish Dabbiru

Hi Everyone I am beginner in java and came across a question like Can I use variables for creating objects and calling methods to reuse the code.

Tesla.java

public class Tesla extends Car {
    @Override
    public void buy(){
        System.out.println("Tesla bought");
        }
     @Override    
     public void sell(){
        System.out.println("Tesla Sold");
        }
}

Ford.java

public class Ford extends Car {
    @Override
    public void buy(){
        System.out.println("Ford bought");
        }
     @Override    
     public void sell(){
        System.out.println("Ford Sold");
        }
}

Car.java

public class Car {
    public static void main(String[] args) {
            String[][] arr = {{"Tesla, Buy"},{"Ford", "Sell"},{"Benz", "Sell"}};
            Car car = new Tesla();
            car.buy();
            Car car = new Ford();
            car.sell();
        }
    
        public void buy() {
            System.out.println("Car bought");           
        }
        
        public void sell() {
            System.out.println("Car Sold");         
        }
    
    }

Here instead of creating each object I just want to use one for loop and create respective object and respective method based on the array elements. Logic like below.

 public static void main(String[] args) {
   String[][] arr = {{"Tesla, Buy"},{"Ford", "Sell"},{"Benz", "Sell"}};
    for(int i = 0;i<arr.length-1;i++){
    Car car = new arr[i][0]();
    car.arr[i][1];
    }
}

How to achieve above logic? Is this something achievable in Java? I searched in google couldn't find relevant questions or problems. Please help me. Thanks in advance.

Note:- I don't want a workaround I just want to know the if logic is achievable using any advanced java concepts I am unaware of.

Basil Bourque

If you want to instantiate objects of various subclasses according to string inputs, you have at least two options:

  • Reflection
  • Builder pattern

Reflection

As commented by Nikolaus, one route is to use Java’s reflection facility. This is the “magic” way, where you would find at runtime the name of the class matching your string input. For example, "Tesla" string would lead you to loading an object of type Class representing the Tesla class you wrote at compile time. You would call methods on that Class object to create an instance of your subclass. In other words, you are programmatically doing a roundabout replacement for the code new Tesla(…).

I do not recommend going the reflection route. This is not “normal” Java app programming. Reflection is usually done only in certain kinds of frameworks and in special rare circumstances.

Builder pattern

The other route more commonly used is the Builder pattern. You define another class called something like CarBuilder. You pass your text values into one or more methods of an object of this type CarBuilder. Those methods validate the inputs.

When done setting up the various pieces of input, you eventually call a method conventionally called build. That method produces and returns an object of type Car. That Car object is actually from a subclass, is actually a Tesla or Ford.

CarBuilder builder = new CarBuilder() ;
builder.setBrand( "Tesla" ) ;
builder.set… = … ;
…
Car car = builder.build() ;  // Actually a `Tesla` subclass object. 

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Calling methods on objects Java

From Dev

Creating objects with methods using 'this' in JavaScript

From Dev

Using objects/calling methods inside event response

From Dev

calling objects from other methods in java

From Dev

Java: methods using array variables

From Dev

Calling methods on objects in an arraylist

From Dev

Calling methods of a Java subclass using Jython

From Java

Creating Arrays of Objects With Methods

From Dev

Multiprocessing for creating objects + calling functions using starmap() Python

From Dev

How to define classes using 2 different objects calling the same methods

From Dev

How to add objects to an array by using their class name, then calling any of their methods?

From Java

Benefits of using static variables and methods in Java

From Dev

Javascript registry for calling methods and objects

From Dev

XPages - Calling Java methods

From Dev

Calling the methods in java

From Dev

Calling Java Methods in XSLT

From Java

Calling multiple methods in Java

From Java

Calling the methods in a class in Java

From Java

Java - Creating an array of methods

From Java

Java question (calling methods with parameters) using UnboundID LDAP SDK api

From Dev

calling different methods of same class using multi threading in java

From Dev

Creating Objects with Different Environment Variables

From Dev

using variables for creating resource

From Dev

Creating interface objects in java

From Java

Creating an array of objects in Java

From Java

Creating objects in Java question

From Java

Creating List of Objects in JAVA

From Dev

Using methods for the objects in class

From Java

How to fix NullPointerException error when calling methods from page objects in selenium testcases using TestNG?

Related Related

  1. 1

    Calling methods on objects Java

  2. 2

    Creating objects with methods using 'this' in JavaScript

  3. 3

    Using objects/calling methods inside event response

  4. 4

    calling objects from other methods in java

  5. 5

    Java: methods using array variables

  6. 6

    Calling methods on objects in an arraylist

  7. 7

    Calling methods of a Java subclass using Jython

  8. 8

    Creating Arrays of Objects With Methods

  9. 9

    Multiprocessing for creating objects + calling functions using starmap() Python

  10. 10

    How to define classes using 2 different objects calling the same methods

  11. 11

    How to add objects to an array by using their class name, then calling any of their methods?

  12. 12

    Benefits of using static variables and methods in Java

  13. 13

    Javascript registry for calling methods and objects

  14. 14

    XPages - Calling Java methods

  15. 15

    Calling the methods in java

  16. 16

    Calling Java Methods in XSLT

  17. 17

    Calling multiple methods in Java

  18. 18

    Calling the methods in a class in Java

  19. 19

    Java - Creating an array of methods

  20. 20

    Java question (calling methods with parameters) using UnboundID LDAP SDK api

  21. 21

    calling different methods of same class using multi threading in java

  22. 22

    Creating Objects with Different Environment Variables

  23. 23

    using variables for creating resource

  24. 24

    Creating interface objects in java

  25. 25

    Creating an array of objects in Java

  26. 26

    Creating objects in Java question

  27. 27

    Creating List of Objects in JAVA

  28. 28

    Using methods for the objects in class

  29. 29

    How to fix NullPointerException error when calling methods from page objects in selenium testcases using TestNG?

HotTag

Archive