Android/Java: Multiple similar classes needing a super class, not sure where to start -
let's 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 application, have need global variable can dynamically generate global scope banana or apple anywhere. the catch is, don't know 1 of these generated, apple, or banana.
i'm guessing need superclass, maybe fruit.java, , instantiate global variable called fruit. when call fruit.getfruitname , fruit.getfruitcolor expect returned apple or banana, whichever randomly generated. don't know how give of these guys parent class.
example of application
public class main extends appcompatactivity { fruit fruit; ... public void randomfruit() { fruit = new fruit(); } public void sometimelater() { if (fruit.getfruitname == "apple"){ // } } }
you can use interface
interface fruit { string getfruitname(); string getfruitcolor(); }
and implement both apple , banana
public class apple implements fruit { @override public string getfruitname() { return "apple"; } @override public string getfruitcolor() { return "red"; } }
and can assign banana or apple fruit fruit
this:
fruit fruit = threadlocalrandom.current().nextboolean() ? new apple() : new banana();
i'd suggest read "inheritance" section of java™ tutorials
Comments
Post a Comment