SSMorgan
SSMorgan

Reputation: 103

Create a method that returns a class and then access the variables

I have a class Fruits that consists of certain variables:

public class Fruits {
  public static String abc="something";
}

public class Apple extends Fruits {
  public static String abc="something";
}

Depending on the config it selects whether it should return an instance of Fruits or Apple:

Class Fruits{
  public static Fruits getfruit{
    if(config==3) {
      return new Apple();
    } else {
      return new Fruits();
    }
  }
}

So later I can use Utility.getfruit().abc.

Upvotes: 0

Views: 183

Answers (2)

gmanjon
gmanjon

Reputation: 1521

If abc is gonna be always the same you can just keep the one in the parent class, you will always be able to access it whether your instance is of a parent or a child class.

If the value of abc is different per child class, create a method public String getAbc() in the parent class and override it in each child that needs a different value:

public class Fruits {
   public static string abc="something";

   public String getAbc() {
      return abc;
   } 
}

public class Apple extends Fruits {
   public static string abc="something different";

   @Override
   public String getAbc() {
      return abc;
   } 
}

And so, in your final call use it this way:

Utility.getfruit().getAbc();

Upvotes: 1

SRM Kumar
SRM Kumar

Reputation: 123

Add a method in the parent class Fruits and override that method in child class Apple .

when you call that method with instance that you got from getfruit will work.

sample code

public class UtilityDemo {​​​​
    static int config = 3;
    public static Fruits getfruit() {​​​​
        if (config == 3) {​​​​
            return new Fruits();
        }​​​​ else
            return new Apple();
    }​​​​

    public static void main(String args[]) {​​​​
        System.out.println(getfruit().getAbc());
    }​​​​
}​​​​


public class Fruits {​​​​
    public static String abc = "From Fruits";
    public String getAbc() {​​​​
        return abc;
    }​​​​
}​​​​


public class Apple extends Fruits {​​​​
    public static String abc = "From Apple";
    @Override
    public String getAbc() {​​​​
        return abc;
    }​​​​
}​​​​

Upvotes: 0

Related Questions