Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSam Katz
2,986 PointsHow do I declare an array of object references?
I need to declare an array using a class type. Cars carsArray[3]
EmployeeFactory.java:7: error: ']' expected Cars carsArray[3]; ^ EmployeeFactory.java:7: error: illegal start of expression Employee carsArray[3];
1 Answer
Caleb Kemp
12,754 PointsSo, if I have a class called "Cars" and I want to create an array of "Cars" with 3 values in it.
Cars [] arrayName = new Cars[3];
general case
Object [] objectName = new Object[3];
Hope that helps P.S. The workspace on this video did not work for me, however, here is a link to a site with a Java emulator on it. https://www.online-java.com/. Here's the code you could paste into it just to see it run.
in Main.java
Cars [] nascar = new Cars[3];
nascar[0] = new Cars("beep");
nascar[0].honk();
in a separate Cars.java
public class Cars {
String horn = "";
public Cars() {
}
public Cars(String horn){
this.horn = horn;
}
public void honk(){
System.out.println(this.horn);
}
}