

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Material Type: Lab; Class: Computer Programming I; Subject: Computer Science; University: Pace University-New York; Term: Spring 2007;
Typology: Lab Reports
1 / 3
This page cannot be seen from the preview
Don't miss anything!
CS121/IS232 Laboratory 3 Using a constructor When you get an instance of a class, a method called a constructor is always executed first. The classes that we have written so far have default constructors. That means that Java provides one for the class that really doesn’t do anything. However, most classes have constructors written by the programmer. These may provide data for variables or run certain methods. For example, we could assign values to the name and age of the panda using a constructor, as follows: public Panda () { name = "Mei Ling"; age = 6; } // constructor Then when the ZooKeeper class gets a new panda, values for the name and age will be given right away. No change has to be made to the ZooKeeper class to do this. The line Panda panda = new Panda (); previously ran the default constructor. Now it will run the one written by the programmer instead. This again hard codes the data into the program. But the constructor can be used more generally as well. We can have the constructor run the getData () method. Since the method is right in the class, we do not have to say which class to use. /*
} // displayData } // Panda Return to the ZooKeeper class and run the project again. You should get the same result as before. The difference is that the values are assigned to the variables in the constructor rather than in the declaration. Methods, including constructors, can have parameters. A parameter is a variable that can be given different values. They are included between the parentheses in the methods declaration. The constructor above can be changed to public Panda (String n, int a) { name = n; age = a; } // constructor But if we add parameters to the constructor in the Panda class, we must also add them to the declaration in the ZooKeeper class where we got a new panda. Panda panda = new Panda ("Mei Ling", 6); Note that the types of the variables are listed in the parentheses in the constructor, they are not in the ZooKeeper class. The main method of the ZooKeeper class is now public static void main(String[] args) { Panda panda = new Panda ("Mei Ling", 6); panda.displayData (); } // main and the constructor in the Panda class is the one shown above.