I'm trying to add let's say 5 classes that they all extend a General class and implements an init() method in a different way.
What I need is a way to store those classes while passing a number of chances for that Class to "happen"
For this I created a Class holder:
public class ClassHolder {
private Class<? extends GeneralOutcome> holdClass;
private int chances;
public ClassHolder(Class<? extends GeneralOutcome> holdClass, int chances) {
super();
this.holdClass = holdClass;
this.chances = chances;
}
public Class<? extends GeneralOutcome> getHoldClass() {
return holdClass;
}
public void setHoldClass(Class<? extends GeneralOutcome> holdClass) {
this.holdClass = holdClass;
}
public int getChances() {
return chances;
}
public void setChances(int chances) {
this.chances = chances;
}
}
Also a GeneralOutcome class that the ones that will be added to a list will extend:
public class GeneralOutcome {
public void init(String text, int times) {
}
}
And the way I'm adding them to a list:
public class Randomizer {
private static List<ClassHolder> myList = new ArrayList<ClassHolder>();
private static ClassHolder outcome01 = new ClassHolder(Outcome01.class, 10);
private static ClassHolder outcome02 = new ClassHolder(Outcome02.class, 10);
private static ClassHolder outcome03 = new ClassHolder(Outcome03.class, 10);
private static ClassHolder outcome04 = new ClassHolder(Outcome04.class, 10);
private static ClassHolder outcome05 = new ClassHolder(Outcome05.class, 10);
public static void main(String[] args) {
for(int i = 0; i < outcome01.getChances(); i++) {
myList.add(outcome01);
}
for(int i = 0; i < outcome02.getChances(); i++) {
myList.add(outcome02);
}
for(int i = 0; i < outcome03.getChances(); i++) {
myList.add(outcome03);
}
for(int i = 0; i < outcome04.getChances(); i++) {
myList.add(outcome04);
}
for(int i = 0; i < outcome05.getChances(); i++) {
myList.add(outcome05);
}
System.out.println(myList.size());
int rand = (int) (Math.random() * myList.size());
System.out.println(rand);
ClassHolder theHoldClass = myList.get(rand);
System.out.println(theHoldClass.getHoldClass());
Class<? extends GeneralOutcome> theOutcome = theHoldClass.getHoldClass();
theOutcome.init();
}
}
The problem is that I'm not able (Don't know how really) cast back to GeneralOutcome to I can access the .init() method.
I get The method init() is undefined for the type Class<capture#3-of ? extends GeneralOutcome>
I know this isn't the best way to do this. So I'm open to both, a fix for this and also what would be a better way to achieve something like this.
What you are trying to do here doesn't work for some reasons.
First of all, your init method isn't static. So that call
Class<? extends GeneralOutcome> theOutcome = theHoldClass.getHoldClass();
theOutcome.init();
leads directly to a compile-time error.
But then, the whole design looks strange. What is the point of holding Class objects in the first place?
Why don't you create an interface
public interface OutcomeFunctionality {
public void foo(String text, int times);
}
to later instantiate objects of whatever class implementing that interface? So that you can finally can deal with lists of such objects (together with those probabilities)?
[ I used the name foo on purpose: alone the strange name "init" makes it very unclear what your code is intended to do! In that sense you should rethink your design, and find better method names to express what those methods will be doing! ]
Long story short: using/holding Class objects doesn't buy you anything in your example code - it only adds complexity. So my advise is: start working there and get rid of that "detour". You might also want to read about the Open/Closed principle - that could give you some guidance how a good OO design looks like that uses abstract classes / subclassing in order to split "behavior" between base and derived classes.
Related
I'd like to create an array of objects where 3 objects are from one class, and a 4th is from second class.
In the first class I did the following:
public class Pupil {
public int n= 0;
Pupil(int n) {
this.n = n;}
}
in the second class I did the following:
public class Tutor {
public int m= 0;
Tutor(int m) {
this.m = m;}
}
In the main class, I created several pupil objects and one tutor object, like this:
public class Main {
public static void main (String[] args) {
//Pupil(n) while for tutor objects it'd be Tutor(m)
Pupil pupil1 = new Pupil(9);
Pupil pupil2 = new Pupil(8);
Pupil pupil3 = new Pupil(6);
Tutor tutor1 = new Tutor(2);
Using objects for printing in main works fine.
But I'd like to create a fourth class where I group them into arrays of objects, but it won't see the objects that I created to create groups out of them. I'm also not sure about the format for creating an array of objects.
public class Groups {
public static void main(String [] args){
Pupil [] g1 = {tutor1, pupil1, pupil2, pupil3};
//cannot resolve any symbols
}
}
EDIT: according to my tutor the groups class should be static to solve this, but I'm not sure how to actually code this?
Edit2: an answer pointed that the array should be Object as the above code would only be able to create an array of pupils, not pupils and tutors objects.
Object [] g1 = {tutor1, pupil1, pupil2, pupil3};
but that still doesn't solve the main issue where no objects are seen from the groups class (//cannot resolve any symbols)
Arrays can only contain the same type of object. With that being said, here is a way:
Object[] g1 = {tutor1, pupil1, pupil2, pupil3};
Java is a strongly typed programming language so you cannot add different type objects to a same collection. But you take advantage of OPP polymorphism principle. You can create a parent class and extend your subclasses from parent class.
Parent Class
public class Group {
}
Child Classes
public class Pupil extends Group {
public int m = 0;
public Pupil(int m) {
this.m = m;
}
}
public class Tutor extends Group {
public int n = 0;
public Tutor(int n) {
this.n = n;
}
}
So this way you can use it as follows:
public class TestSchool {
public static void main(String[] args) {
Pupil pupil1 = new Pupil(9);
Pupil pupil2 = new Pupil(8);
Pupil pupil3 = new Pupil(6);
Tutor tutor1 = new Tutor(2);
Tutor tutor2 = new Tutor(2);
Group[] groupArray = {pupil1, pupil2, pupil3, tutor1, tutor2};
}
}
I'm learning SOLID principles with Java and I'm trying to implement two classes with this. My problem is about ISP. I have some methods that is present in one class but not in the other and I also have to refer both classes with the same interface.
This is the first class:
public final class Complex implements Number {
#Override
public String polarForm() {
//This class needs to implement this method
}
#Override
public String rectangularForm() {
//This class needs to implement this method
}
}
Here is the second one:
public final class Real implements Number {
#Override
public String polarForm() {
//This class does not need this method!
}
#Override
public String rectangularForm() {
//This class does not need this method!
}
}
Finally I have to refer to the classes something like this:
public static void main(String[] args) {
Number c = new Complex();
Number r = new Real();
Number n = c.add(r);
System.out.println(c.polarForm());
System.out.println(n);
}
How can I refer to both classes with the same interface without implementing unnecessary methods?
An alternate solution to approach this problem would be to use Composition instead of Inhertiance in conjunction to the interface segregation principle.
Number class
public class Number {
private RectangleForm rectangleForm;
private PolarForm polarForm;
private BigDecimal value;
public Number(RectangleForm rectangleForm, PolarForm polarForm,BigDecimal value) {
this.rectangleForm = rectangleForm;
this.polarForm = polarForm;
this.value = value;
}
public String polarForm() {
return polarForm.transform(this.value);
}
public String rectangleForm() {
return rectangleForm.transform(this.value);
}
//other methods such as add and subtract
}
PolarForm interface
public interface PolarForm {
public String transform(BigDecimal number);
}
RectangularForm interface
public interface RectangleForm {
public String transform(BigDecimal number);
}
RectangleForm implementation for real numbers
public class RectangleFormReal implements RectangleForm {
#Override
public String transform(BigDecimal number) {
String transformed = "";
//transfromed = logic to transform to rectangle form
return transformed;
}
}
PolarForm implementation for Real numbers
public class PolarFormReal implements PolarForm {
#Override
public String transform(BigDecimal number) {
//return the number as is without any transformation
return number.toString();
}
}
Putting the pieces together
public class NumberTest {
public static void main(String[] args) {
RectangleForm rf = new RectangleFormReal();
PolarForm pf = new PolarFormReal();
Number number = new Number(rf, pf,new BigDecimal(10));
String rectangleForm = number.rectangleForm();
String polarForm = number.polarForm();
}
}
You can create the PolarFormComplex and RectangleFormComplex implementations and wire theNumber instance in a similar fashion. The advantage of this approach is that your code will always rely on the interface of the Number class (by interface I mean the public APIs) and you can chose the transformation strategy by injecting the corresponding PolarForm or RectangleForm instances into your Number instance at compile time as shown above or at runtime (via a factory)
Break your Number interface (or base class) into multiple interfaces. The standard operations (add, subtract, etc) are in one; let's say INumber. polarForm and rectangularForm are part of another; let's say IComplex.
Real would implement INumber; Complex would implement INumber and Icomplex. You could then treat both as INumber.
If necessary, you could also create another interface that implements both.
I have a similar question on this topic but I dumbed it down and left out all the extra code. Also, I took the advice of the old question and set my variables to zero but it didn't make any difference.
Main:
public class WhyAPrints0Main {
public static void main(String[] args) {
int x = 24;
WhyAPrints0 set = new WhyAPrints0();
WhyAPrints01 get = new WhyAPrints01();
set.setWhy(x);
get.print();
}
}
Class 1
public class WhyAPrints0 {
private int why;
public int getWhy() {
return why;
}
public void setWhy(int why) {
this.why = why;
}
}
Class 2
public class WhyAPrints01 {
WhyAPrints0 get = new WhyAPrints0();
int a = 0;
public void print(){
a = get.getWhy();
System.out.println(a);
}
}
I really don't understand why this doesn't print 24 so if someone could explain well and possibly fix the code to where it does I would really appreciate it.
Why would you expect it to print 24?
You invoke the print() method:
get.print();
Which prints 0:
public class WhyAPrints01 {
WhyAPrints0 get = new WhyAPrints0();
int a = 0;
public void print(){
a = get.getWhy();
System.out.println(a);
}
}
(Since 0 is the default value for an int, which is what is returned by get.getWhy().)
I think your confusion is coming from the concept of having multiple instances of the same class. You have two different instances of WhyAPrints0. One in your main() method and one in your second class. These two instances have nothing to do with one another. Setting a value in one doesn't affect the other.
As an analogy, consider two identical cars. If you put something in the trunk of one car, you shouldn't expect to retrieve it from the trunk of the other car. It doesn't matter that the cars are otherwise identical, they're not the same car.
You have to link your WhyAPrints01 to your WhyAPrints0 some how. Right now you have 2 instances of WhyAPrints0. You can change your WhyAPrints01 to something like this so you can set an instance of WHyAPrints0 in your WhyAPrints01 class.
public class WhyAPrints01 {
WhyAPrints0 get;
int a = 0;
public WhyAPrints01(WhyAPrints0 get){
this.get = get;
}
public void print(){
a = get.getWhy();
System.out.println(a);
}
}
And your main to:
public static void main(String[] args) {
int x = 24;
WhyAPrints0 set = new WhyAPrints0();
set.setWhy(x);
WhyAPrints01 get = new WhyAPrints01(set);
get.print();
}
I am very new to programming and have a question about using variables in what I believe to be called "nested classes."
class BeginningGameTest {
int attack;
int defend;
public static class James
{
attack = 25;
defend = 15;
}
public static class Janet
{
attack = 45;
defend = 1;
}
public static class Jackson
{
attack = 10;
defend = 20;
}
public static void main(String[] args) {
System.out.prinln(James.attack);
}
}
Do I have the general idea down? I would like to save variables that are the "same" thing, but are different from class to class and are accessed differently like in the print line. I do get a few errors, what should I do to keep the same concept and still keep it fairly simple so I could understand it? Are there any easy to understand tutorials for people who are new to programming in general?
Thanks in advance!
The design of this seems incorrect.
What you're trying to go for when working in an object-oriented language is the basic model of something you wish to represent.
Those three static classes seem to represent the same type of object, so let's create a simple model for them. Think of models like a cookie-cutter. Every cookie cut with this will be the same generic "shape", but will have different characteristics about it (sprinkles, frosting beard, etc). This model should be in its own separate file.
public class Player {
private String name;
private int attack;
private int defense;
public Player(String theirName, int theirAttack, int theirDefense) {
name = theirName;
attack = theirAttack;
defense = theirDefense;
}
// create getters and setters for their attack and defense
}
To actually make use of it, you'd want to instantiate the object.
public class BeginningGameTest {
public static void main(String[] args) {
Player p1 = new Player("James", 25, 15);
Player p2 = new Player("Janet", 45, 1);
Player p3 = new Player("Jackson", 10, 20);
// interactions with the objects below
}
}
Some superb beginner resources already exist in the Java tag wiki; give those a thorough reading. Try new things out, and don't be afraid to ask (good) questions about things you don't understand.
You should create an inner class then define instances of that class within the main method.
public class BeginningGameTest {
public static void main(String[] args) {
Player james = new Player(25,15);
Player janet = new Player(45,1);
Player jackson = new Player(10,20);
System.out.println(james.getAttack());
}
}
class Player{
int attack;
int defend;
public Player(int attack, int defend){
this.attack = attack;
this.defend = defend;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getDefend() {
return defend;
}
public void setDefend(int defend) {
this.defend = defend;
}
}
You should use the concept of instances to distinguish persons, rather than defining a class for each person. You can define a single class "Person" and instantiate James, Jackson etc. To give them each different attack/defence values, you can use constructors with arguments.
I feel that you might benefit from reading an introduction to object oriented programming. Try searching for "object oriented programming".
You can go two ways about this. You could create subclasses such that James, Janet and Jackson are all classes of the same type, being BeginningGameTest. For example, James could be:
public class James extends BeginningGameTest
{
public James()
{
attack = 25;
defend = 15;
}
}
What I think you want James, Janet and Jackson to be, are not subclasses, but rather instances of the same class BeginningGameTest, like this:
BeginningGameTest James = new BeginningGameTest();
James.setAttack(25);
James.setDefend(15);
There are a few concepts you should read upon:
Classes vs instances
Inheritance
And I also implicitly introduced you to the concept of setters (and getters), typical for Java beans.
This will work:
public static class James
{
static int attack = 25;
static int defend = 15;
}
// ...
Then this would work:
public static void main(String[] args)
{
System.out.prinln(James.attack);
}
This is probably a better design:
public class Player()
{
public static enum NAME { JAMES, JANET };
int attack, defend;
public Player(NAME name)
{
switch (name)
{
case JAMES:
attack = 25;
defend = 15;
break;
// ...
}
}
public static void main(String[] args) throws Exception
{
System.out.println(new Player(NAME.JAMES).attack);
}
}
This is a better design for realistic requirements: (allowing run-time creation of players)
int attack, defend;
String name;
public Player(int attack1, int defend1, String name1)
{
attack = attack1;
defend = defend1;
name = name1;
}
What you can simply do is create different objects of your class that will hold different values of variables attack and defend. Here is the code for the same.
/* package whatever; // don't place package name! */
class Main
{
int attack,defend;
public Main(int attack,int defend)
{
this.attack=attack;
this.defend=defend;
}
public void show()
{
System.out.println("attack: "
+attack+" defend: "+defend);
}
public static void main (String[] args) throws java.lang.Exception
{
Ideone James = new Main(125,15);
James.show();
Ideone Janet = new Main(45,1);
Janet.show();
Ideone Jackson = new Main(10,20);
Jackson.show();
}
}
say I have a class A which is as follows
public class A {
protected static float[] floatArray = null;
protected static Map<Integer, float[]> history = new HashMap<Integer,float[]>();
protected static Integer historyCount = 0;
public void runEverySecond(Populator objPopulator) {
floatArray = objPopulator.getValues();
history.put(historyCount, floatArray);
historyCount++;
}
}
and Class B looks as follows
public class B {
private A objA;
protected final static Populator objPopulator = new Populator();
public void run(Integer numOfTime) {
for(int i = 0; i < numOfTime; i++)
objA.runEverySecond(objPopulator);
}
}
and Class Populator looks as follows
public class Populator {
protected float[] randomValues = new float[2];
public float[] getValues() {
randomValues[0] = //some new random float value generated for every call
randomValues[1] = //some new random float value generated for every call
return randomValues;
}
}
and class containing main looks as follows
public class MainClass {
public static void main() {
final B objB = new B();
objB.run(10);
}
}
Here is the problem I am facing, the Map history contains the same value for every entry in the map. I want the Map history to store all the values generated by objPopulator.getValues() method. How do I do it?
Some help would be really appreciable.
Thanks in Advance :)
The Actual code (with irrelevant code removed ) represented by class A
public class MySuperAgent implements Agent {
protected static float[] marioFloatPos = null;
protected static Map<Integer, float[]> levelRecord = new HashMap<Integer, float[]>();
protected static Integer mapCount = 0;
/* protected static int testCount = 0;
protected static float[] testx = new float[2];
protected static float[] testy = new float[2];*/
#Override
public void integrateObservation(Environment environment) {
marioFloatPos = environment.getMarioFloatPos();
levelRecord.put(mapCount, marioFloatPos);
mapCount++;
/*if(testCount < 2){
testx[testCount] = marioFloatPos[0];
testy[testCount] = marioFloatPos[1];
testCount++;
} else {
testCount = 0;
}*/
}
}
class C represent environment object
integrateObservation method is called from class similar to class B
if I use the code within the comment block then I am able to record only 2 past values of x and y of Mario. I need a way to store all the values of x and y of Mario :)
Every entry in your Map has a reference to the same static field floatArray as its value.
Instead of having floatArray as a static member variable in A consider:
public void runEverySecond(Populator objPopulator) {
float[] floatArray = objPopulator.getValues();
history.put(historyCount, floatArray);
historyCount++;
}
EDIT Also I don't know how your code for class A would compile as it is. Shouldn't runEverySecond take a Populator parameter instead of Object? See revised snippet above.
There's only one floatArray and you keep reassigning it.
This code was almost impossible to follow in a reasonable way--what a mess.