How to return an object from different classes in Java?

java return object reference
how to return an instance of a class java
how to pass class object as parameter in java
class name as return type in java
java pass class type as parameter
passing object as parameter in java program
return a class in java
object class in java

I'm beginner in Java and I need help. I have several classes.

public class A{
  private String name = "A";

  public String getClassName(){
   return "A";
 }

  public void editClassName(String name){
   this.name = name;
  }
}

public class B{
  private String name = "B";
  private int counter = 0;

  public String showClassName(){
    return "B";
  }

  public int getCount(){
    return counter;
  }
}

Such classes could be more. I also need to have some class witch can return an instance of asked class.

public class ClassSelector{
  public static ??? getClassByName(String nameOfClass){
   if(nameOfClass == "A"){ return new A();}
   if(nameOfClass == "B"){ return new B();}
  }
}

And here is a code that I want to use to get access to appropriate class:

ClassSelector.getClassByName("A").getClassName();
ClassSelector.getClassByName("B").showClassName();

I need to have an access to the instance of the class, and each instance can show it's unit methods that class has.

In this situation I don't get which return type I should use in the 'getClassByName' method. I will very appreciate for help.

I would very much like to offer an alternative architecture if possible! It's not much different to what you have.

Firstly, we'll define some interface.

public interface Named {
    String getName();
}

Now, this means you can have lots of concrete classes but provided they implement this interface, you'll know (and the Java compiler will know) that they have the getName method available to you.

Next, let's update your class to implement this interface.

public class A implements Named {
    public String getName() {
        return "A";
    }
}

You could do this for classes B, C... and so on.

Now your method return type can be set to Named, that is:

public class ClassSelector{
  public static Named getClassByName(String nameOfClass){
   if(nameOfClass.equals("A")){ return new A();}
   if(nameOfClass.equals("B")){ return new B();}
  }
}

And you can access the response like so:

Named response = ClassSelector.getClassByName("A").getName();

Passing and Returning Objects in Java, While creating a variable of a class type, we only create a reference to an object. Thus, when we pass Passing Objects as Parameters and Returning Objects. From the method one object to initialize another. Box(Box ob). Returning Objects In java, a method can return any type of data, including objects. For example, in the following program, the incrByTen () method returns an object in which the value of a (an integer variable) is ten greater than it is in the invoking object.

As Eran suggested, it can be only of type Object, because they don't have a common superclass other than Object. If you don't want to work with Object class, you can create a body-less interface and implement it in both(or multiple classes) and that can be your return type.

After the call of the method, you can find the specific type of the returned object with instanceof;

Java - Returning Objects from methods - Java, Next, we create another Cube variable obj2 and call the getObject() method of obj1 which returns an object of the Cube class. Then we are printing out the values� How to return object after a method call in Java. Now we will learn how to return an object after a method call. It seems to be strange. But it’s true that A method can return any type of data, including class types that you create. We will understand how it happens with the following example given below.

Retrieving Class Objects (The Java™ Tutorials > The Reflection API , There are several ways to get a Class depending on whether the code has access to The value returned by getClass() is the Class corresponding to java. io. Method is returning the reference of the object. When we are writing the following code Cube obj2 = obj1.getObject (); in the above example, the called method getObject () of obj1 object is returning the reference of the newly created object. So, obj2 is getting the reference of the newly created object. ← Prev.

First of all, please note that for string comparison you have not to use "==" (the problem is in nameOfClass == "A" and so on, I say it only for completeness).

I want suggest a solution based on reflection, that maybe could be more concise:

public interface IClass {

}

public class A implements IClass {
    private String name = "A";
}

public class B implements IClass {
    private String name = "B";
}

public class ClassSelector {

    public static void main(String[] args) {
        IClass obj = null;
        try {
            Class c = Class.forName("A");
            obj = (IClass) c.newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        System.out.println("Create object of type " + obj.getClass());
    }

}

Returning a Value from a Method (The Java™ Tutorials > Learning , You declare a method's return type in its method declaration. Rectangle class that was discussed in the sections on objects returns an integer: However, an Object is not necessarily a Number — it could be a String or another type. Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. We will be explaining about all these in the access modifiers chapter. Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes.

Thanks to all guys, who have answered my. Forgive me, when I create the first post, I made one mistake, which leads to misunderstanding what I mean. Now the code in the first post is better to show what I'm looking for.

Java returning object - Java Tutorials, Returning the Object From Method In Java Programming A method can return any type of data, including class types that you create. For example, in the following program, the getRectangleObject( ) method returns an object. throws an exception (covered later), whichever occurs first. You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.

How to return multiple objects from a Java method?, Yes, we can return multiple objects from a method in Java as the method always encapsulates the objects public class CustomObject<Obj> { By the way, all Java objects are polymorphic because each object is an Object at least. We can assign an instance of Animal to the reference variable of Object type and the compiler won’t complain: Object object = new Animal(); That’s why all Java objects we create already have Object specific methods, for example, toString().

The Method Declaration, Java requires that a method declare the data type of the value that it returns. class Stack { static final int STACK_EMPTY = -1; Object[] stackelements; Java supports method name overloading so multiple methods can share the same name. Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a Class does not extend any other class then it is direct child class of Object and if extends other class then it is an indirectly derived. Therefore the Object class methods are available to all Java classes.

Returning Objects From Methods in Java, Like any other data datatype, a method can returns object. Program (Sample. java) public class Sample { private int value; public Sample(int i) { value = i; }� Using a POJO class instance This is the most commonly used method to return multiple values from a method in Java. The idea is to return an instance of a class containing all fields we want to return.

Comments
  • It can only be Object, since that's the only common super class of A and B
  • Note that getClassByName is misleading, since your method returns an instance of a class. getInstanceByClassName would be a better name
  • Thank you, Eran. Yes you are right, getInstanceByClassName is better.
  • Seems like a builder design pattern or factory may be.
  • In the if condition instead of nameOfClass == "A" it should be "A".equals(nameOfClass)
  • Thank you guys for help. It is almost what I need. I see that I made some mistake in the code example which lied to misunderstanding. I will change the code to what I meant.
  • @Jack Hi Jack, if this solves your problem, could you please accept the answer? Thanks.
  • Hi Christopher, unfortunately no, this is not wnat I need. I made changes in the first post, where add some additional things, which shown better what I searching.