You will see more examples like this in later lessons. If a constructor has an object instance variable, it can copy the referenced object in the parameter using new and the constructor of the referenced object like below so that it does not change the state of the original object. When you pass object references as parameters to constructors or methods, they become aliases for the original object and can change it. For example, a Person class could have an Address object as an instance variable, and the Address class could have String instance variables for the street, city, and state. The examples above have instance variables that are primitive types, but you can have other objects, reference types, as instance variables. String expect = "Car model: \nCar year: 2019\nCar model: Honda\nCar year: 2010" īoolean passed = getResults(expect, output, "Running main") Ĭonstructors are used to set the initial state of an object by initializing its instance variables. Public class RunestoneTests extends void testMain() throws IOException call the constructor to create 2 new Car objects using the 2 constructors. set the instance variables to the init parameter variables Public Car(String initModel, int initYear) set the instance variables to default values "" and 2019 Run your program and make sure it works and prints out the information for both cars. The car1 object should test the first constructor with default values and the car2 object should test the second constructor to create a Honda 2010 car. And fill in the code to call the constructors in the main method numbered 3. Fill in the code for the 2 constructors that are numbered 1 and 2. The following class defines a Car with the instance variables model and year, for example a Honda 2010 car. Public class RunestoneTests extends void test() throws IOExceptionīoolean passed = getResults(expect, output, "Running main", true) Test Code for Lesson 5.2.0.1 - Fraction Public Fraction(int initNumerator, int initDenominator) constructor: set instance variables to init parameters constructor: set instance variables to default values Hint! Remember to start with the main method! You can also view it in the Java visualizer by clicking on the Code Lens button below. Try to guess what it will print before you run it. Variable values to 1 rather than 0 – so we don’t end up with divide by zero. Note that this constructor sets the default instance The following class defines a Fraction with the instance variables numerator and denominator.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |