Josh Beckwith Josh Beckwith - 3 months ago 18
Android Question

Android/Java: Multiple similar classes needing a super class, not sure where to start

Let's say I have 2 similar classes:

Apple.java

public class Apple {
public string getFruitName(){
return "apple";
}
public string getFruitColor(){
return "red";
}
}


Banana.java

public class Apple {
public string getFruitName(){
return "Banana";
}
public string getFruitColor(){
return "yellow";
}
}


In my application, I have a need for a global variable so I can dynamically generate a global scope banana or an apple anywhere. The catch is, I don't know which one of these is generated, it could be an apple, or a banana.

I'm guessing I need a superclass, maybe Fruit.java, and instantiate a global variable called fruit. When I call fruit.getFruitName and fruit.getFruitColor I would expect to be returned an apple or a banana, whichever was randomly generated. I just don't really know how to give all of these guys a parent class.

Example of my application

public class main extends AppCompatActivity {
Fruit fruit;

...

public void randomFruit() {
fruit = new Fruit();
}

public void sometimeLater() {
if (fruit.getFruitName == "apple"){
//
}
}
}

Answer

You can use an interface

interface Fruit {
    String getFruitName();
    String getFruitColor();
} 

And then just implement it for both apple and banana

public class Apple implements Fruit {
    @Override
    public String getFruitName() {
        return "apple";
    }

    @Override
    public string getFruitColor() {
        return "red";
    }
}

And then you can assign banana or apple to Fruit fruit like this:

Fruit fruit = 
    ThreadLocalRandom.current().nextBoolean() ? new Apple() : new Banana();

I'd suggest you to read "Inheritance" section of The Java™ Tutorials

Comments