Java OOP; creating array of objects - java

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};
}
}

Related

I need a way to randomize outcomes passing and holding classes

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.

How to set and get with three Classes?

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();
}

Count Number of Objects in Java

I am creating a program called Humans and Pets. The program simply prints out a list of Human's names (in this case I have created 4) and their corresponding pets. Here is the code:
AmazingPets.java
public class AmazingPets {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Welcome to Pets and Humans! Created By Marc B.\n____________________________\n");
Dogs firstDog = new Dogs("Ghost");
Humans firstName = new Humans("Alex");
Dogs secondDog = new Dogs("Paperbag");
Humans secondName = new Humans("Michael");
Cats firstCat = new Cats("Tom");
Cats secondCat = new Cats("Mr Furball");
Humans thirdName = new Humans("Bryan");
Humans fourthName = new Humans("Julie");
System.out.printf("%s's dog's name is %s.\n", firstName.getHumanName(), firstDog.getDogName());
System.out.printf("%s's dog's name is %s.\n", secondName.getHumanName(), secondDog.getDogName());
System.out.printf("%s's cat's name is %s.\n", thirdName.getHumanName(), firstCat.getCatName());
System.out.printf("%s's cat's name is %s.\n", fourthName.getHumanName(), secondCat.getCatName());
}
}
Humans.java
public class Humans {
private String mHumanName;
public Humans(String humanName) {
mHumanName = humanName;
}
public String getHumanName() {
return mHumanName;
}
}
I would like to create a class method called populationCount for Humans that would return the total number of Humans instances created. I would then like to output the result (using a Scanner in AmazingPets.java) to have the number of counts in the console.
Can anyone please suggest possible ways to return the total number of Humans made? as I cannot seem to find any resources online. Thank you in advance. :)
You can use this abstract class, in order to count any type of objects that inherits it. The answer is based on addy2012's answer (Thanks!):
public abstract class Countable
{
private static final Map<Class<?>, Integer> sTotalCounts = new HashMap<>();
public Map<Class<?>, Integer> getCountsMap() {
return sTotalCounts;
}
public int getTotalCount()
{
return sTotalCounts.get(this.getClass());
}
public Countable()
{
int count = 0;
//Add if it does not exist.
if(sTotalCounts.containsKey(this.getClass()))
{
count = sTotalCounts.get(this.getClass());
}
sTotalCounts.put(this.getClass(), ++count);
}
}
Then, you can do:
public class Dogs extends Countable {/**/}
public class Cats extends Countable {/**/}
public class Humans extends Countable {/**/}
Then, you can instantiate any of your objects
Dogs dog = new Dogs("...");
Dogs dog2 = new Dogs("...");
Cats cat = new Cats("...");
Humans human = new Humans("...");
You can then get each total count by invoking the getTotalCount method from an instance:
System.out.println(dog.getTotalCount());
System.out.println(cat.getTotalCount());
System.out.println(human.getTotalCount());
Which will give you
2
1
1
Important Notes:
1) getTotalCount() is invoked via instances (non-static). This might be strange semantically, as you have a method returning a result for a total of instances, so any modification on this would be nice.
2) In order to allow the count on different types, map get & put operations are applied. Those operations have their own complexities and might be costly at cases. For more information on this, look in this answer.
Create a static field private static int humanCount = 0 and increment it in the constructor:
public class Humans {
private String mHumanName;
private static int humanCount = 0;
public Humans(String humanName) {
mHumanName = humanName;
humanCount++;
}
public String getHumanName() {
return mHumanName;
}
public static int populationCount() {
return humanCount;
}
}
You can add a finalize() method and use it to decrement the count. It will be called when the object is destroyed.
protected void finalize( ) throws Throwable {
humanCount--;
super.finalize();
}

Java scheduling causing an error

This code is supposed to fetch the variables from my class Course.
public void prettyPrint(){
Course myCourse = new Course(myCourse.n, myCourse.days, myCourse.start, myCourse.end);
for (int i=0; i>Courses.size();i++){
System.out.println("---"+ Course.dayString + ' '+ ' '+" ---");
System.out.println(myCourse.start +"-"+ myCourse.end+ ": " + myCourse.n );
}
This gets me errors that say "myCourse.n may not be initalized." How do I initialize them if they are just pulling the info from the Course class?
Course myCourse = new Course(myCourse.n, myCourse.days, myCourse.start, myCourse.end); // myCourse is just a reference, when you call new , myCourse hasn't been initialized.
Maybe you should code like this:
Course myCourse = new Course(n, days, start, end);
You cannot reference values in an object before creating it. However, you can create static class variables and reference them without creating any objects as shown:
class Course{
static int n = 1;
static int days = 180;
//..other definitions
//..
}
class Main{
public static void main(){
Course myCourse = new Course(Course.n, Course.days);
}
}
However, static variables introduce dependency between instance variables. A better design would be the factory design pattern with a sample implementation as follows:
class Course{
int n;
int days;
// other instance definitions
public course(int n, int days){
this.n = n;
this.days = days;
}
}
class History extends Course{
public History(){
super(10,200);//the values that you want this course to have
}
}
class Geography extends Course{
public Geography(){
super(20,100);//the values that you want this course to have
}
}
class Main{
public static void main(String args[]){
Course history = new History();
Course geography = new Geography();
}
}

Using variables in a nested class JAVA

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();
}
}

Categories

Resources